Ajax calling a java Rest API - java

I am having ajax problems that I cannot figure out, and need some help... I am using Spring for my REST api and my ajax calls don't seem to work... I have searched the forums and haven't been able to find an answer:
My java Spring api is as follows:
#Controller
#RequestMapping("api")
public class RecentRestController {
RecentService recentService;
#Autowired
public void PersonRestController(RecentService recentService) {
this.recentService = recentService;
}
/**
* Add recent lake, then get recently viewed lakes and users ordered by timestamp
* #param handle
* #return
*/
#RequestMapping(value = "recent/weather/{auser}/{temp}/{windspeed}/{winddeg}/{laketag}", method = RequestMethod.GET)
#ResponseBody
public RecentlyViewedList getRecentlyViewedLakes(#PathVariable String auser, #PathVariable Integer temp,
#PathVariable Integer windspeed, #PathVariable Integer winddeg, #PathVariable String laketag) {
RecentlyViewedList rvl = recentService.getRecentlyViewedWeather(auser, temp, windspeed, winddeg, laketag);
return rvl;
}
When I use ajax to call this Java REST from ajax it doesn't seem to work. My ajax call looks as follows from html/php:
new $Ajax.Request('http://localhost:8080/server/api/weahter/lake/' + agruments.auser + '/' + arguments.windspeed +'/' + arguments.winddeg + '/' + arguments.laketag, {
type : "GET",
//:url : recenturl,
//cache : false,
async : false,
crossDomain: true,
dataType : 'jsonp',
//data: arguments,
success : function(recent) {
alert("SUCESS");
var i=0;
var lakecount = recent.lake.length;
var usercount = recent.user.length;
alert("lakecount:" + lakecount);
alert("usercount:" + usercount);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("An error has occurred making the request: " + errorThrown);
},
});
It never seems to work. It never calls my REST api correct.. What am I doing incorrectly?
Something is wrong with how I calling my REST service..
Any help is greatly appreciated..
Thanks in advance.

As you are checking for a #GET request, the most obvious thing to do is to try to hit the API directly from a browser ( type in your URL field
http://localhost:8080/server/api/weahter/lake/' + agruments.auser + '/' + arguments.windspeed +'/' + arguments.winddeg + '/' + arguments.laketag
with the parameters resolved ).
Other thing you should be checking is that your context path is 'server' as that is where the URL is pointing.
Also you have and spelling error in the first parameter of the URL: 'agruments' instead of 'arguments'

Yeah, the request has recent in it. What I cannot figure out is that if I build it manualy:
url : 'http://localhost:8080/server/api/recent/lake/nightstalker/3/3/3/TXFORK'
it works. But when I build it with variables, it does not.

Related

unable to pass map to restful method

I am trying to call this API via postman:
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void printDetails(final MultivaluedMap<String, String> formParams) {
for(String key : formParams.keySet()) {
System.out.println(key + " " + formParams.get(key));
}
}
But the map turns out to be empty. Please help me with the same.
PS: This is the first time I am trying to pass variable number of parameters to the api. I have referred to
sending List/Map as POST parameter jersey and How to access parameters in a RESTful POST method.
I think my mistake is in the way I am passing the parameters in postman: postman image
Please help me with the same. Also please help with how to call this API via an ajax (in JS) call.
Set the request header as "application/x-www-form-urlencoded".
Request body - Select raw and provide values as mentioned below:-
{
"LOCATION": "Singapore"
}
I have found out one possible answer.
#POST
public void printDetails() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
Map<String, String[]> mapp = request.getParameterMap();
for(String key : mapp.keySet()) {
System.out.println(key + " " + mapp.get(key)[0]);
}
}
Still not sure how to do it by passing "final MultivaluedMap" in the arguments

Cannot get angular $http to work

I'm trying to get a simple angularjs login screen to work.
The angular app sends the login details via http get method to a java servlet and anticipates a json response with success/fail. The java servlet is running on Tomcat 8.0.
Unfortunately, the angular app doesn't seem to be able to receive data from the servlet (it does send the data to the servlet) - the errorCallback method of "then" is called everytime.
Also, accessing the servlet's url directly from the browser works fine (the browser shows the response string).
Can you help me to find the problem?
This is the div element in the html page:
<div ng-controller = "loginCtrl">
<input type="text" ng-model = "userName" placeholder="Username"></input><br>
<input type = "text" ng-model = "userPass" placeholder="Password"></input><br>
<button type = "button" ng-click = "login()">Login</button><br>
{{message}}
</div>
This is the js code:
var expenseApp = angular.module("expenseApp",[]);
expenseApp.controller('loginCtrl',['$scope','$http',function($scope,$http) {
$scope.userName = "";
$scope.userPass = "";
$scope.message = "type in your credentials";
$scope.login = function() {
var address = "http://localhost:8080/ExpenseSystemServer/LoginServlet?userName=" + $scope.userName + "&userPass=" + $scope.userPass;
$http({method:'get',
url:address})
.then(function(data, status, headers, config) {
$scope.message = "http success";
},
function(data, status, headers, config) {
$scope.message = "http error";
});
};
}]);
And this is the servlet doGet method in java (the servlet's class name is LoginServlet):
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
String userName = request.getParameter("userName");
String userPass = request.getParameter("userPass");
System.out.print("Login attempt with " + userName + "; " + userPass + ": ");
if (userName == null || userPass == null || !userName.equals("admin") || !userPass.equals("pass")){
response.getWriter().write("{'success':false,'message':'wrong details'}");
System.out.println("failed.");
}
else {
response.getWriter().write("{'success':true, 'user':{'name':'admin'},'message':'Hi admin!'}");
System.out.println("succeeded.");
}
}
Can you help me here?
Thanks.
You're sending invalid JSON from the servlet. JSON keys and string values must be in double quotes, not single quotes. Use JSONLint to validate your JSON. Or better, create a Java object, and a marshaller like Jackson to transform the object to valid JSON.
Also, instead of sending back a successful response (with code 200), with an object property "success" set to false, you should return an error response (400 if the required credentials are not there at all, 401 if they're not valid). Doing that not only shows respect for the HTTP protocol, but allows using http promises as intended:
http(...).then(successCallback, errorCallback)
instead of
http(...).then(successButActuallyMaybeErrorCallback, anotherErrorCallback)
Your JSON is invalid using single quotes that should be double
It's a really bad practice to create your own when most languages can encode it for you from native arrays and objects. I don't know best way using java but it needs to look like:
response.getWriter().write('{"success":false,"message":"wrong details"}');
note switch of single and double quotes

Ajax call returns string for Highcharts series but result is wrong (parsing error?)

I'm developing a Java Spring-Hibernate application that uses Highcharts. I've got a JavaScript function that, when called, it makes an Ajax call to get the chart data (series) and creates the chart with it:
<!-- Stacked bar chart -->
<script type="text/javascript">
//Function that plots the highcharts chart
function plot(park) {
$.ajax({
type: "get",
url: "MainView/report/datagaps/" + park,
dataType: "text",
error: function (error) {
console.log(error);
alert('Error while requesting datagaps for ' + park + ' : ' + error);
},
success: function (result) {
$("#chart" + park).highcharts({
chart: {
type: 'column'
},
series: result
});
}
});
}//END_FUNCTION
</script>
I've removed most of the plot options code, so you see the most relevant code above. There is a model method that deals with this request:
#RequestMapping(value = "/datagaps/{parkName}", method = RequestMethod.GET)
public #ResponseBody String datagaps(#PathVariable String parkName, Map model, HttpSession session) {
LOGGER.debug("Successfully called datagaps for '" + parkName + "'");
LOGGER.debug((String) session.getAttribute("chartData"+parkName));
return (String) session.getAttribute("chartData"+parkName);
}//END_METHOD
The method is quite simple: a session string variable is returned, which is the one that should be used in series: result.
The thing is that this generates an unexpected result:
However, if I set a model variable session.setAttribute("chartData" + park, rrdao.getParkData().get(park)); before loading the form and I use it instead of the result like series: ${chartDataAA}, it works:
This is quite weird, since the data used is exactly the same: both ajax call and model variable come from the same place, and they are logged before beign send, which allows me to be sure data is good. This data has a format like [{name:'AA01', data: [[1412114400000,0],[1412200800000,0],[1412287200000,0],[1412373600000,0],[1412460000000,0],[1412546400000,0],[1412632800000,0]}]
I bet is some kind of string parsing problem when it is returned from the ajax call, perhaps due to the single quotations, but I don't know how to deal with it.
Please help!
Maybe it is misspelling, but your single serie which you have as missing bracket in data array. It should be: [{name:'AA01', data: [[1412114400000,0],[1412200800000,0],[1412287200000,0],[1412373600000,0],[141246‌​0000000,0],[1412546400000,0],[1412632800000,0]] }]
Change: dataType: "text" to dataType: "json"
Then in the controller if you use jackson json just return a List

REST disregards any part that is not English characters , when receiving UTF-8

Sending ajax request in UTF8 to the server that uses REST , disregards any part that is not English characters
I'm using JAVA with REST on the server side , and the client sends ajax requests in UTF8 , that includes Hebrew words .
The AJAX request :
var clientNumber = '12344432432';
var userID = '321321321';
var someHebrewWord = ...;
var someEnglishWord = ....;
var servletUrl = '/Management/services/manager/' + clientNumber + '/' + userID + '/' + someEnglishWord + '/' someHebrewWord;
alert('Sending this :' + servletUrl);
$.ajax({
url: servletUrl,
type: 'POST',
cache: false,
data: { },
success: function(data){
alert('Return value is:' + data);
window.location = "./replyPage.html";
}
, error: function(jqXHR, textStatus, err){
alert('text status '+textStatus+', err '+err + " " + JSON.stringify(jqXHR));
}
});
On the server side , I use REST :
#Produces({ "application/json" })
#Path("/manager")
public class Management {
#POST
#Path("{clientNumber }/{userID }/{someEnglishWord}/{someHebrewWord}")
#Produces("application/json")
public boolean insert(#PathParam("clientNumber") String clientNumber, #PathParam("userID") String userID,
#PathParam("someEnglishWord") String someEnglishWord, #PathParam("someHebrewWord") String someHebrewWord)
{
// do some stuff
}
#POST
#Path("{clientNumber }/{userID }/{someEnglishWord}")
#Produces("application/json")
public boolean updateSomething(#PathParam("clientNumber") String clientNumber, #PathParam("userID") String userID , #PathParam("someEnglishWord") String someEnglishWord)
{
// do other stuff
}
// more code
}
So , when the AJAX request is sent , the updateSomething() is invoked instead of insert() ,
even though I'm sending 4 fields , and not 3 !
What causes this , and how can I fix it ?
Much appreciated
Allowed characters in a URL is restricted. You have to encode the URL with encodeURIComponent.
A better option might be posting those parameters in a data -variable and using #FormParam instead of #PathParam.

How to create a Java Servlet for a given jQuery.ajax () call?

I have a file called wfd.proxy.js that contains the following lines of code :
if (!WFD) { var WFD = {}; };
if (!WFD.Proxy) { WFD.Proxy = {}; };
WFD.Proxy =
{
SERVICE_URL : "/delegate/WFD/WFService?",
PDF_SERVICE_URL : "/delegate/pdf-exporter?",
DATA_TYPE : "json", // used by jQuery
DATA_TYPE_EXT : "ajax", // used by ExtJs
DATA_TYPE_TXT : "text", // used for tests
SaveWorkflow : function(code)
{
jQuery.ajax({
url: WFD.Proxy.SERVICE_URL + "task=savemodel",
data: { code : code },
dataType : WFD.Proxy.DATA_TYPE,
type: 'POST',
success : function(data) {
WFD.Proxy.OnSaveWorkflowCallback(data);
},
error : function(jqXHR, textStatus, errorThrown) {
alert("Errore di comunicazione: " + errorThrown);
}
});
}
,
WFD.Proxy.OnSaveWorkflowCallback = function(data)
{
/*
data.response
data.message
data.model_new_id
data.idsNodes[i].original_id
data.idsNodes[i].new_id
*/
}
};
I have written the code that converts an xml file to JSON format. The JSON string that i get from the code I've written until now, should be passed as the code parameter of SaveWorkflow : function(code) .
I'm not really sure what do I have to do at this point.
I did some searches and saw that jQuery.ajax() calls where manipulated using Java Servlets ...
Any idea how to resolve this please?
Thanks in advance
What you've written is client side code (i.e. executes in your browser). The part that's missing is the server side. Your "ajax call" is making an asynchronous connection to a web server, using this URL:
/delegate/WFD/WFService?task=savemodel&code=xxxx
xxxx is the value of the code variable. Your javascript is expecting a text string as response from this URL.
You don't need a servlet per se to handle this. Any web server that accepts the ajax URL and returns the required data will do (e.g. PHP...)
If you need a servlet and you don't know how to build one, I think you have a lot of reading to do.
I suggest:
https://www.google.be/search?q=my+first+servlet

Categories