使用Spring的JQuery / Ajax的JSON请求

我是JSON / Spring MVC的新手,我想尝试一个简单的例子来调用Spring MVC控制器的AJAX – 但是我一直都会返回400错误 – 错误请求。

在浏览互联网之后,我发现这通常是由于没有设置适当的内容类型 – 但[我相信]我已经这样做了。

这是我的AJAX电话:

//validate the object var urlString = "/ajax/add/"; $.ajax({ type:"POST", url: urlString, contentType: "application/json; charset=utf-8", dataType: "json", data: {value1: 'apples', value2 : 'oranges'}, success: function(result){ alert("success"); }, error: function(jqXHR, textStatus, errorThrown){ alert("error:" + textStatus + " exception:" + errorThrown); } }) ; 

而我的控制器:

 @Controller itpublic class AddController { private static Logger m_log = null; @RequestMapping(value = "/ajax/add") public String handle(@RequestBody String json){ DummyClass dummyRequest; try { ObjectMapper mapper = new ObjectMapper(); dummyRequest = mapper.readValue(json, DummyClass.class); m_log.info("Value1: " + dummyRequest.getValue1()); m_log.info("Value2: " + dummyRequest.getValue2()); } catch (Exception e) { } finally{ } return "called"; } 

谁能帮我吗?

编辑

这是我用来配置Spring的上下文:

     <!-- -->                           <!--  --> 

我应该注意到我在com.project.do.working包中有一个带Ajax的工作控制器,但是带有Ajax和JSON的非工作控制器在同一个包com.project.do.not.working中

我认为您的请求映射没有将RequestMethod作为POST。 我想默认情况下它接受一个get请求,但你的AJAX是一个POST请求。 尝试更改如下

 @RequestMapping(value = "/ajax/add", method = RequestMethod.POST) public String handle(@RequestBody String json){ } 
 @Controller @RequestMapping("/employee/add.htm") public class EmployeeController { @RequestMapping(method = RequestMethod.POST) public @ResponseBody Employee add(HttpServletRequest request, HttpServletResponse response) throws Exception { } }