How to get AJAX values in Java - java

I'm doing an ajax call to my server, and need to get the values from it. How is this done?
This is the ajax:
$.ajax({
type: "POST",
url: "http://localhost:8080/myapp/etc",
contentType: "application/json; charset=utf-8",
data: {"id": "1", "somekey": "somevalue"},
dataType: "json",
async: "true",
success: function(msg) {
alert("success " + msg);
},
error: function(msg) {
alert("error " + msg.toString());
}
});
I'm working with Restlets so I'm assuming the values would be in the Representation entity. This is the method:
#Post
public Representation doPost(Representation entity) {
String et = java.net.URLDecoder.decode(entity.getText(), "UTF-8");
System.out.println("the entity text " + et);
}
This prints out "id": "1", "somekey": "somevalue". But how do I get the other values? The async, the url, etc?

Restlet will give you access about the elements sent within the request (URL, headers, payload) but not to client-side configuration properties to build the request.
You can have a look at what is sent in the request for your AJAX call using tool like Chome console or Firebug.
The property async isn't sent within the request, so you can't get it from server side. For the URL, you can use this code within a server resource:
Reference reference = getRequest().getResourceRef();
String url = reference.toString();
For more details, have a look at javadocs for the class Reference: http://restlet.com/technical-resources/restlet-framework/javadocs/2.1/jee/api/org/restlet/data/Reference.html. This class allows you to have access to each element within it (host domain, port, path, ...).
Hope it helps you,
Thierry

The async is a client-side directive telling the client not to block while the ajax call is processed. The server doesn't know or care about this.
Getting the URL is possible server side using something like String url = ((HttpServletRequest)request).getRequestURL().toString();

you can do something like this, using the org.restlet.ext.json extension:
#Post
public Representation handle(JsonObject jo) {
System.out.println(jo.getString("id"));
System.out.println(jo.getString("somekey"));
return ...;
}

Related

Spring REST API, Pass a primitive type to the controller

#CrossOrigin(origins = "http://localhost:3000")
#GetMapping("")
public ResponseEntity<List<ToDoItemViewModel>> loadCategoriesByName(#RequestParam(required = false) String name)
{
List<ToDoItemViewModel> allItemsByCategoryName = toDoItemService.getAllItemsByCategoryName(name);
return new ResponseEntity<>(allItemsByCategoryName, HttpStatus.OK);
}
How can i pass just a primitive type to the controller, here is how my $.ajax looks like
$.ajax({
method: 'GET',
url: "http://localhost:8080/todItems",
contentType: 'application/json',
crossDomain: true,
data: 'Work',
success: (resp) => {
console.log(resp)
},
error: (resp) => {
console.log(resp);
}
})
Now when i debug it, it indeed sends the request to this controller, but the String name is always null for some reason, can you just show me what i have to adjust in my ajax request, it's probably something in the data field.
You are using GET Request with request params(#RequestParam annotation).
#RequestParam means that param in request pass across url, like this;
http://localhost:8080/todItems?name=Work
So, you just need to move data to url params.
If you prefer send data across request body, please do not use GET method, use POST instead. Many web servers are not supporting request body in GET Requests

POST jersey with HeaderParam annotation

I get null when I send a POST. Please someone know how to pass value with Angular using #HeaderParam in Jersey?
I have this in backend:
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Users loginUser(#HeaderParam("username")String username,#HeaderParam("password") String password){
System.out.println("What happen"+userService.loginService(username, password));
return userService.loginService(username, password);
}
and this in front-end, using Angular:
$scope.getUserFunction = function () {
$http({
method : 'POST',
url : 'http://localhost:8080/JersyBackEnd/resources/login'+data,
contentType:'application/json',
data : {username: "akram",password:"yes"},
})
.then(function(data) {
console.log(data);
});
};
I get 204 because of the null data.
Can anyone help me, either using HeaderParam, PathParam or FormParm annotations in Jersey?
data is sent as the request body. What you really want is headers.
From the docs:
data – {string|Object} – Data to be sent as the request message data.
headers – {Object} – Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent. Functions accept a config object as an argument.
Example:
$http({
...
headers: {
username: "akram",
password: "yes"
}
})
When you use #HeaderParam, you have to pass the values from .JS using headers: { 'something': 'anything' }. As i can see currently you are using data : {username: "akram",password:"yes"}. try to use headers: { 'something': 'anything' } instead of this.
Please try header, hope it will solve your null issue.

Cookie not being passed on subsequent requests

I am having a problem with passing a cookie while trying to make subsequent requests with AJAX to my Spring MVC controller.
For e.g. I have a /login endpoint to which I pass some JSON via POST method and it sets the cookie. I see the cookie in the firebug:
As you can see it is there. I am creating a cookie like this:
NewCookie cookie = new NewCookie(new Cookie(SECURITY_TICKET, encodedTicket, configKey, null), null, (int) TimeUnit.MINUTES.toSeconds(expireTime), expireTimeDate, false, false)
And setting it to HTTP headers:
httpHeaders.add(HttpHeaders.SET_COOKIE, cookie.toString());
Then these headers are being added to ResponseEntity like this:
ResponseEntity entity = new ResponseEntity<>(this.entity, this.httpHeaders, this.status)
And this response entity is returned. My conroller's methods are all REST based.
So then I am trying to call the other (/search) endpoint after successful login which functionality is expecting the cookie and it obviosly fails because for some reason cookie is not being passed back.
My AJAX calls looks like this:
$(function () {
$.ajax({
url: 'http://localhost:8080/dev-citigroup-citi/login',
type: 'POST',
dataType: 'json',
data: '{ "username": "client1", "password": "*******", "platform": "iOS", "UUID": "321321321", "application": "CitiReach", "applicationVersion": "1.0" }',
success: function (data, status, xhr) {
$.ajax({
url: 'http://localhost:8080/dev-citigroup-citi/search/eventattendee?q=*:*&start=0&rows=1&wt=json&indent=true',
type: 'GET',
xhrFields: { withCredentials:true },
success: function (data, status, xhr) {
console.log(data);
},
error: function (jqXHR) {
console.log(jqXHR);
}
});
},
error: function (jqXHR) {
console.log(jqXHR);
}
});
});
As I mentioned the /login is OK but the other call fails. I am adding xhrFields: { withCredentials:true } which should be including the cookie in the /search request but for some reason it is not.
I also have CORS being set up correctly:
Access-Control-Allow-Origin: http://localhost:63342
Access-Control-Allow-Credentials: true
http://localhost:63342 is the origin where the request comes from, it is configured in the CORS headers.
Any idea what might be wrong here?
I found the solution, so rather than having xhrFields: { withCredentials:true } on the method level, I've put it globaly:
$.ajaxSetup({
xhrFields: {
withCredentials: true
}
});
And cookie is passed now within the subsequent requests. No idea why it doesn't work on method level, maybe a bug in jquery...
jQuery version I was using: 2.1.3
Maybe this will help someone in future.

Calling Restful Web service using jQuery ajax doesnt work

I am using restful web service and trying to query it from jquery ajax call
RESTAPI
#GET
#Path("/dynamicReports")
#Produces("application/json")
public String getDynamicFilters() {
String JsonStr=null;
JSONObject json=new JSONObject();
JSONObject tempjson=new JSONObject();
tempjson.put("number", 200);
json.put("response", tempjson);
JsonStr=json.toString();
System.out.println("inputJson : "+JsonStr);
Response.ok().header("Access-Control-Allow-Origin", "*").build();
return JsonStr;
}
My jquery ajax call
$.ajax({
type: "GET",
dataType:"jsonp",
crossDomain: true,
url: "http://url:port/DynamicReportsService/dynamicReports",
success: function(data1) {
console.log("response:" + data1);
},
error: function(jqXHR, textStatus, errorThrown) {
$("#loadingimageid").remove();
alert('generateReportFromMR:Error in processing!');
console.log(jqXHR);
}
});
In browser if i try the url it gives me {"response":{"number":200}}. but ajax call gives an error and in web console it shows the json with error.
When you use jsonp you need to use the callback parameter which the browser sends to give the response.
Setting the dataType to jsonp will allow jQuery to automatically add an extra ?callback=? to the end of your URL to specify the callback.
Basically the call expects the result to be of jsonp format but you only return json format. By enclosing your json inside the callback parameter you ensure that jsonp is returned and not json.
When you check the console, the GET request will be contain something like
?callback=jQuery152035532653917078266_4305276802416
Now all you need to do is use 'jQuery152035532653917078266_4305276802416' and you should give a response like,
jQuery152035532653917078266_4305276802416({"response":{"number":200}});
So in Java, you can use request.getParameter("callback") and then use that to return a jsonp.
return request.getParameter("callback") + "(" + jsonStr + ");";
If you want to use custom callback then your ajax request should be like,
$.ajax({
type: "GET",
dataType:"jsonp",
crossDomain: true,
url: "http://url:port/DynamicReportsService/dynamicReports",
jsonpCallback: 'successCallback',
success: function(data1) {
console.log("response:" + data1);
},
error: function(jqXHR, textStatus, errorThrown) {
$("#loadingimageid").remove();
alert('generateReportFromMR:Error in processing!');
console.log(jqXHR);
}
});
And response be,
return "successCallback(" + jsonStr + ");";

Ajax json POST and Spring MVC Controller

I have ajax json POST method like this
$.ajax({
type: 'POST',
url: "localhost:8080/webeditor/spring/json/",
data: JSON.stringify(contents),
dataType: "json"
});
Controller to handle post request
JSONPObject json;
BindingResult result = new BeanPropertyBindingResult( json , "MyPresentation" );
#RequestMapping(value="json/", method = RequestMethod.POST)
public void savePresentationInJSON(Presentations presentation,BindingResult result) {
//do some action
}
but I getting this error
XMLHttpRequest cannot load localhost:8080/webeditor/spring/json/. Cross origin requests are only supported for HTTP.
I'm not sure how to correct above error.
My final work version
var jsonfile={json:JSON.stringify(contents)};
$.ajax({
type: 'POST',
url: "/webeditor/spring/json/",
data: jsonfile,
dataType: "json"
});
AJAX, and
#RequestMapping(value = "/json/", method = RequestMethod.POST)
public void saveNewUsers( #RequestParam ("json") String json)
{
System.out.println( json );
}
Passing JSON with Spring is fairly straight forward. Consider the following jQuery function:
function processUrlData(data, callback) {
$.ajax({
type: "GET",
url: "getCannedMessageAsJson.html",
data: data,
dataType: "json",
success: function(responseData, textStatus) {
processResponse(responseData, callback);
},
error : function(responseData) {
consoleDebug(" in ajax, error: " + responseData.responseText);
}
});
}
Now use the following String #Controller method...
#RequestMapping(value = "/getCannedMessageAsJson.html", method = RequestMethod.POST)
public ResponseEntity<String> getCannedMessageAsJson(String network, String status, Model model) {
int messageId = service.getIpoeCannedMessageId(network, status);
String message = service.getIpoeCannedMessage(network, status);
message = message.replaceAll("\"", """);
message = message.replaceAll("\n", "");
String json = "{\"messageId\": \"" + messageId
+ "\", \"message\": \"" + message + "\"}";
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
}
In my case the request is so simple that I'm just hardwiring the json formatting in the controller method, but you could just as easily use a library like Jackson to produce the json string.
Also as others have stated, verify that the "value" in the #RequestMapping is a unique, legitimate filename. With the json method I show above you don't have to have a corresponding jsp page (in fact it won't use one).
In the URL : url: "localhost:8080/webeditor/spring/json/"
webeditor must be war name or service name so in ur #RequestMapping(value="/webeditor/spring/json/" i think u should not have 'webeditor' it must be only /spring/json
normally 404 means the for the URL requst is wrong or no such service is running for that URL
Looks like jQuery so why not try
$.getJSON('webeditor/spring/json', JSON.stringify(contents, function(data) {//do callbackstuff});
If you wanted to request cross domain the way to do it is like :-
cbFn = function(data) {
// do callback stuff.
}
var ca = document.createElement('script');
ca.type = 'text/javascript';
ca.async = true;
ca.src = server + '/webeditor/spring/json.jsonp?callback=cbFn';
var s = document.getElementsByTagName('head')[0];
s.parentNode.insertBefore(ca, s);
and also add the servlet mapping
<servlet-mapping>
<servlet-name>yourSevletName</servlet-name>
<url-pattern>*.jsonp</url-pattern>
</servlet-mapping>
Your application should have a context root, which would precede the rest of your URL path. And you should also have a servlet-mapping defined in web.xml which defines which requests get directed to your Spring controllers. So if the context root of your application is "myapp" and your servlet-mapping is going to *.html, then your ajax call would look like this:
$.ajax({
type: 'POST',
url: "/myapp/webeditor/spring/json.html",
data: JSON.stringify(contents),
dataType: "json",
success: function(response) {
// Success Action
}
});
In yr jsp include the tag library like so
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
Then create a full url using spring
<c:url var="yourFullUrl" value="/webeditor/spring/json/" />
then create javascript variable based on this so you can use in Ajax
<script>
var yourUrl= '<c:out value="${yourFullUrl}"/>';
</script>
No use the javascriptvariable representing the url :
<script>
$.ajax({
type: 'POST',
url: yourUrl,
data: JSON.stringify(contents),
dataType: "json"
});
</script>

Categories

Resources