Spring - #RequestBody blocks the requests? - java

I am new to Spring . From my previous search in google says that we can send JSON data to the Spring Controller using the #RequestBody and we can get the data in the controller.
But when I used the #RequestBody , It doesn't allow the request to the controller .
function sendJSON(){
var jsonData = {"name":"XXX","age":"20","hobby":"TV"};
/alert("json Data : \n\n\n"+jsonData);
$.ajax({
type: 'POST',
dataType: 'json',
url: contexPath + "/sender.html",
//dataType: "html",
//contentType: "application/x-www-form-urlencoded; charset=utf-8",
contentType: "application/json"
data : JSON.stringify(jsonData),
success: function(data, textStatus ){
alert("success");
$("#result").html(data.name+"data.age+" "+data.hobby);
},
error: function(xhr, textStatus, errorThrown){
//alert('request failed'+errorThrown);
}
});
}
My controller will be ,
#RequestMapping(value = "sender.html", method=RequestMethod.POST)
public #ResponseBody Person sendMessage(#RequestBody Persons person){
System.out.println("Test..........");
System.out.println(person.getName()+ " "+person.getAge()+" "+person.getHobby()+"\n");
return persons;
}
But my request blocks.
Am I sending the correct json data to the controller that matches the java bean ?
Hope our stack users will help me.

You need jackson-mapper-asl on your classpath. If you use maven add this to your pom:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>

Please check your java bean class name that matches the JSON data.

You have multiple errors in the code. I've assumed that you're using this kind of Person:
public class Person {
private int age;
private String hobby;
private String name;
/* omitted getters/setters */
}
It's a little bit unclear form your code what do you want your controller to return - single person or a list of them. I've changed it to return one person:
#RequestMapping(value = "sender.html", method = RequestMethod.POST)
public #ResponseBody
Person sendMessage(#RequestBody Person person) {
System.out.println("Test..........");
System.out.println(person.getName() + " " + person.getAge() + " " + person.getHobby() + "\n");
return person;
}
And now the javascript. Instead of contextPath you can just use url without starting slash. There was also missing comma and wrong quotation marks. Here is the corrected version:
var jsonData = {
"name" : "XXX",
"age" : "20",
"hobby" : "TV"
};
$.ajax({
type : 'POST',
dataType : 'json',
url : "sender.html",
contentType : "application/json",
data : JSON.stringify(jsonData),
success : function(data, textStatus) {
alert("success");
$("#result").html(data.name + data.age + data.hobby);
}
});

Do not use JSON.stringify on your data. You should use the plain javascript object. Then, if it still does not work, look at the logs, maybe your json model does not match your java bean.

Shouldn't the content type be "application/json" and not "application/form encoded". Have you tried changing it. Its strange that you don't get any server side exceptions. What response do you get back?

It's hard to say without seeing your Person and Persons objects. You could turn on the debugging for spring. I find it very helpful. From my log4j config
<logger name="org.springframework.web.servlet.mvc" >
<level value="debug" />
</logger>
I would also check in Firebug or the Chrome dev tools that you are sending the correct payload to the server.

Related

Posting a JSON to a Spring Controller

I'm learning to pass a JSON object through ajax to a Spring Controller.
Found an article, that seems to explain how its done: http://hmkcode.com/spring-mvc-json-json-to-java/
From that point i added a #RequestMapping to the Controller:
#RequestMapping(value = "/get-user-list", method = RequestMethod.POST)
public #ResponseBody String testPost(#RequestBody ResourceNumberJson resourceNumberDtoJson) {
System.out.println(">>>>>>>>>>>>>>>>>>>>>> I AM CALLED");
return "111";
}
Then i'm forming my ajax post:
var json = {
"login" : "login",
"resource_number" : "111",
"identifier" : "1111",
"registrator_number" : "11111111111111"
};
console.log(JSON.stringify(json));
$.ajax({
type : "POST",
url : "/get-user-list",
dataType : "text",
data : JSON.stringify(json),
contentType : 'application/json; charset=utf-8',
mimeType: 'application/json',
success: function(data) {
alert(data.id + " " + data.name);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
which is runned from "get-user-list" page.
When i'm trying to run this, i recieve a HTTP 415 error. Spring 4, Jackson 2.4
Cant understand what i'm doing wrong.
HTTP 415 means, that the media type is not supported.
Try changing your #RequestMapping annotation to
#RequestMapping(value = "/get-user-list",
method = RequestMethod.POST,
consumes="application/json")
You should also consider testing your REST-service with a client like RESTClient, Postman or even cURL to make sure it is working correctly before you start implementing the jQuery client.

How to pass JSON object from ajax to controller in spring mvc?

I am using spring mvc. I need to pass a json object from my jsp page to controller.
My ajax code:
function createJSON() {
jsonObj = [];
item = {};
$(".values").each(function() {
var code = $(this).attr('id');
item[code] = $('#' + code).val();
});
var content=JSON.stringify(item)
$.ajax({
type: 'POST',
contentType : 'application/json; charset=utf-8',
url: "/pms/season/submit",
data: content,
dataType: "json",
success : function(data) {
alert(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
}
My controller code:
#RequestMapping(value = "/submit", method = RequestMethod.POST)
public void saveNewUsers( #RequestParam ("json") String json) {
System.out.println( "json ::::"+json );
}
But it's not working.
#RequestParam("json") means that you are intending to include a request parameter called json in the URI, i.e. /submit?json=...
I think you intend to get the request body, i.e. #RequestBody.
I would then suggest that, unless you really need the raw JSON string, you would have the #RequestBody translated to a Java object for you:
public void saveNewUsers(#RequestBody MyDto myDto) {
...
}
where MyDto would have getters/setters and fields matching the JSON class.
You can over omit the #RequestBody annotation if you annotate the controller with #RestController, instead of #Controller.
If you definitely want the raw JSON string, then take a look at this previous question: Return literal JSON strings in spring mvc #ResponseBody

How to get AJAX values in 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 ...;
}

can not able to call spring controller using ajax

I am trying to call a spring controller using ajax, but can not able to go to the controller. I am getting Error 405 Request method 'POST' not supported error. I am keeping my code here please give suggestion to come over it
this is my ajax code calling controller from jsp page, here i am getting the anchor attribute value.
basic.jsp
function organizationData(anchor) {
var value = anchor.getAttribute('value');
$.ajax({
url : "manageOrganization",
method : "GET",
dataType: "json",
contentType: 'application/json',
data: {organizationId : value },
success : function(response) {
alert(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
}
controller
#RequestMapping(value="/manageOrganization", method = RequestMethod.GET)
public String organizationData(#RequestParam String organizationId) {
return organizationId+" associated";
}
here i should get the string to the jsp as a ajax response, but i am getting the error message. Any body can help me.
Regards Sree
For json response you need to add #ResponseBody annotation to your controller method.
You need to use type:"GET" not method:"GET" try it like,
$.ajax({
url : "manageOrganization",
type : "GET", // its type not method
dataType: "json",
.....
Read jQuery.ajax()
Also check that you are returning a json or not.
Your controller is returning String which may be resolved into some other jsp file IF you have configured viewResolver in spring configuration file. Try adding #ResponseBody like this:
#RequestMapping(value="/manageOrganization", method = RequestMethod.GET)
public #ResponseBody
String organizationData(#RequestParam String organizationId) {
return organizationId+" associated";
}

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