如何将json数据发送到Spring Controller?

时间:2014-01-14 13:32:43

标签: ajax spring spring-mvc

我正在使用Spring MVC 3.0.7。我使用AJAX将数据发送到我的Spring控制器,但不调用spring控制器。这是我的Ajax调用:

var mysaverowurl = '/app/user/save';
$.ajax({
  url: mysaverowurl,
  type: "POST",
  data: postData,
  contentType: 'application/json',
  success: function () {
    alert("success ");
  }
}); 

postData包含{"name":"Franck","age":"94"}

这是我的Spring控制器:

@Controller
@RequestMapping("/app/user")
public class myController {
    @RequestMapping(value = "/save", method = RequestMethod.POST, headers = { "Content-type=application/json" })
    @ResponseBody
    public List<String> saveUser(HttpServletRequest request, Model model, @RequestBody User user) {
        List<String> reponse = null;
        // ...........
        return reponse;
    }
}

未调用控制器。但是如果从@RequestBody签名中删除saveUser

public List<String> saveUser(HttpServletRequest request, Model model)

它被调用。为什么@RequestBody似乎不起作用?

用户类:

    public class User{

    private String name;

    private String age;

    public String getAge(){
      return age;
     }
    public void setAge(String age){
    this.age=age;
}
    public String getName(){
      return name;
     }
    public void setAge(String name){
    this.name=name;
}

    }

这是我的pom文件的一部分。

        <dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-lgpl</artifactId>
                 <version>1.8.1&</version>
</dependency>
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

1 个答案:

答案 0 :(得分:0)

var mysaverowurl = '<c:url value="/app/user/save" />';更改为

var mysaverowurl = '/app/user/save';