JQuery,Spring MVC @RequestBody和JSON - 使它协同工作 [英] JQuery, Spring MVC @RequestBody and JSON - making it work together
问题描述
我想要一个双向JSON到Java序列化
我正在使用成功 Java到JSON到JQuery路径。 。( @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){
//做点什么
});
此作品好(例如注释工作已经完成,感谢所有回答者)
但是,如何执行反向路径:使用RequestBody将JSON序列化为Java对象?
无论我尝试什么,我都无法得到这样的东西:
@RequestMapping(value = {/ fooBar / save},method = RequestMethod.POST)
public String saveFooBar(@RequestBody FooBar fooBar,
HttpServletResponse response,ModelMap model){
//永远不会调用此方法。 (当我删除RequestBody时它会...)
}
我已配置Jackson正确的(它在出路时序列化)我将MVC设置为当然驱动的注释
如何使其工作?它有可能吗?或者Spring / JSON / JQuery是单向的(出)?
更新:
我更改了这个Jackson设置
< bean id =jsonHttpMessageConverter
class =org.springframework.http。 converter.json.MappingJacksonHttpMessageConverter/>
<! - 将Rest服务的返回值绑定到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>
建议的(几乎相似的)
< 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
) p>
参见:
以下是一个工作示例:
Maven POM
< project xmlns =http://maven.apache.org/POM/4.0.0xmlns: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/j2eexmlns:xsi =http://www.w3.org/2001/XMLSchema-实例
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/弹簧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/mvcxmlns :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)
公共类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());
返回结果;
}
}
Request.java
公共类请求实现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
公共类结果实现Serializable {
private static final long serialVersionUID = -5054749880960511861L;
private int addition;
private int减法;
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来测试此设置:在命令行上运行
,然后发送POST请求:
URL:http:/ / localhost:8080 / test / math
mime类型:application / json
post body:{left:13,right:7}
我使用了海报Firefox插件可以做到这一点。
这是响应的样子:
{addition:20,减法:6,乘法:91}
I would like to have a bidirectional JSON to Java serialization
I'm using successfully the Java to JSON to JQuery path... (@ResponseBody
)
e.g.
@RequestMapping(value={"/fooBar/{id}"}, method=RequestMethod.GET)
public @ResponseBody FooBar getFooBar(
@PathVariable String id,
HttpServletResponse response , ModelMap model) {
response.setContentType("application/json");
...
}
and In JQuery I use
$.getJSON('fooBar/1', function(data) {
//do something
});
this works well (e.g. annotations work already, thanks to all the answerers)
However, how do I do the reverse path: have JSON be serialized to a Java Object back using RequestBody?
no matter what I try, I can't get something like this to work:
@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...)
}
I have Jackson configured correctly (it serializes on the way out) and I have MVC set as annotations driven of course
How do I make it work? is it possible at all? or is Spring / JSON / JQuery is oneway (out)?
Update:
I changed this Jackson setting
<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>
To the (almost similiar one) suggested
<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>
And it seems to work! I don't know what exactly did the trick, but it works...
I'm pretty sure you only have to register MappingJacksonHttpMessageConverter
(the easiest way to do that is through <mvc:annotation-driven />
in XML or @EnableWebMvc
in Java)
See:
Here's a working example:
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>
in folder 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>
in folder 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>
In folder 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; }
}
You can test this setup by executing mvn jetty:run
on the command line, and then sending a POST request:
URL: http://localhost:8080/test/math
mime type: application/json
post body: { "left": 13 , "right" : 7 }
I used the Poster Firefox plugin to do this.
Here's what the response looks like:
{"addition":20,"subtraction":6,"multiplication":91}
这篇关于JQuery,Spring MVC @RequestBody和JSON - 使它协同工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!