简体   繁体   中英

Spring - @RequestBody blocks the requests?

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>

请检查与JSON数据匹配的Java bean类名称。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM