JQuery,Spring MVC @RequestBody和JSON – 使它们一起工作
我想有一个双向的JSON到Java序列化
我正在成功使用Java到JSON到JQuerypath…( @ResponseBody
)例如
@RequestMapping(value={"/fooBar/{id}"}, method=RequestMethod.GET) public @ResponseBody FooBar getFooBar( @PathVariable String id, HttpServletResponse response , ModelMap model) { response.setContentType("application/json"); ... }
和我在使用JQuery
$.getJSON('fooBar/1', function(data) { //do something });
这工作得很好 (例如注释已经工作,谢谢所有的答复者)
但是,如何做相反的path:使用RequestBody将JSON序列化为Java对象?
无论我尝试什么,我都无法得到这样的工作:
@RequestMapping(value={"/fooBar/save"}, method=RequestMethod.POST) public String saveFooBar(@RequestBody FooBar fooBar, HttpServletResponse response , ModelMap model) { //This method is never called. (it does when I remove the RequestBody...) }
我有jacksonconfiguration正确(它序列化的出路),我有MVC设置为注释驱动当然
我如何使它工作? 有可能吗? 或者是Spring / JSON / JQuery是单向的(out)?
更新:
我改变了这个jackson设置
<bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /> <!-- Bind the return value of the Rest service to the ResponseBody. --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <util:list id="beanList"> <ref bean="jsonHttpMessageConverter" /> <!-- <ref bean="xmlMessageConverter" /> --> </util:list> </property> </bean>
到(几乎类似的)build议
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="jacksonMessageConverter" /> </list> </property> </bean>
它似乎工作! 我不知道这个伎俩究竟是什么,但它的工作原理
我很确定你只需要注册MappingJacksonHttpMessageConverter
(最简单的方法是通过XML中的<mvc:annotation-driven />
或Java中的@EnableWebMvc
)
看到:
- 这个论坛post和
- 7.6.5在Spring MVC中configuration格式化
这是一个工作的例子:
Maven POM
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>json</artifactId><packaging>war</packaging> <version>0.0.1-SNAPSHOT</version><name>json test</name> <dependencies> <dependency><!-- spring mvc --> <groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>3.0.5.RELEASE</version> </dependency> <dependency><!-- jackson --> <groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.4.2</version> </dependency> </dependencies> <build><plugins> <!-- javac --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version><configuration><source>1.6</source><target>1.6</target></configuration></plugin> <!-- jetty --><plugin><groupId>org.mortbay.jetty</groupId><artifactId>jetty-maven-plugin</artifactId> <version>7.4.0.v20110414</version></plugin> </plugins></build> </project>
在文件夹src / main / webapp / WEB-INF中
web.xml中
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> <servlet><servlet-name>json</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>json</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app>
JSON-servlet.xml中
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <import resource="classpath:mvc-context.xml" /> </beans>
在文件夹src / main / resources中:
MVC-的context.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <mvc:annotation-driven /> <context:component-scan base-package="test.json" /> </beans>
在src / main / java / test / json文件夹中
TestController.java
@Controller @RequestMapping("/test") public class TestController { @RequestMapping(method = RequestMethod.POST, value = "math") @ResponseBody public Result math(@RequestBody final Request request) { final Result result = new Result(); result.setAddition(request.getLeft() + request.getRight()); result.setSubtraction(request.getLeft() - request.getRight()); result.setMultiplication(request.getLeft() * request.getRight()); return result; } }
Request.java
public class Request implements Serializable { private static final long serialVersionUID = 1513207428686438208L; private int left; private int right; public int getLeft() {return left;} public void setLeft(int left) {this.left = left;} public int getRight() {return right;} public void setRight(int right) {this.right = right;} }
Result.java
public class Result implements Serializable { private static final long serialVersionUID = -5054749880960511861L; private int addition; private int subtraction; private int multiplication; public int getAddition() { return addition; } public void setAddition(int addition) { this.addition = addition; } public int getSubtraction() { return subtraction; } public void setSubtraction(int subtraction) { this.subtraction = subtraction; } public int getMultiplication() { return multiplication; } public void setMultiplication(int multiplication) { this.multiplication = multiplication; } }
您可以通过执行mvn jetty:run
来testing此设置mvn jetty:run
在命令行上mvn jetty:run
,然后发送POST请求:
URL: http://localhost:8080/test/math mime type: application/json post body: { "left": 13 , "right" : 7 }
我使用海报Firefox插件来做到这一点。
以下是响应的样子:
{"addition":20,"subtraction":6,"multiplication":91}
另外你还需要确定你有
<context:annotation-config/>
在您的SPringconfigurationxml中。
我也会build议你阅读这篇博文。 它帮助了我很多。 http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/
更新:
只是检查我的工作代码,我有@RequestBody工作正常。 我的configuration中也有这个bean:
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="jacksonMessageConverter"/> </list> </property> </bean>
可能会很高兴看到Log4j在说什么。 它通常会提供更多信息,根据我的经验,如果请求的内容types不是Application / JSON,则@RequestBody将失败。 您可以运行Fiddler 2来testing它,甚至Mozilla Live HTTP头插件也可以帮助您。
除了这里的答案…
如果你在客户端使用jQuery,这对我有用:
Java的:
@RequestMapping(value = "/ajax/search/sync") public String sync(@RequestBody Foo json) {
Jquery(你需要包含Douglas Crockford的json2.js才能有JSON.stringify函数):
$.ajax({ type: "post", url: "sync", //your valid url contentType: "application/json", //this is required for spring 3 - ajax to work (at least for me) data: JSON.stringify(jsonobject), //json object or array of json objects success: function(result) { //do nothing }, error: function(){ alert('failure'); } });
如果你不想自己configuration消息转换器,你可以使用@EnableWebMvc或者<mvc:annotation-driven /> ,将Jackson添加到类path中,Spring将会为你提供JSON,XML和其他一些转换器默认。 另外,您还将获得一些其他常用的转换,格式和validationfunction。
如果您愿意使用Curl来调用JSON 2和Spring 3.2.0,请在这里查看 FAQ。 AnnotationMethodHandlerAdapter已被弃用,并被RequestMappingHandlerAdapter所取代。