JQuery,
Spring MVC @RequestBody and JSON - 集成整合
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
See:
•this forum post and
•5.6.4 Configuring Formatting in Spring MVC
--------------------------------------------------------------------------------
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}
分享到:
相关推荐
本项目"Java后台服务器Maven+SpringMVC+Ajax+@RequestBody+Json传输"就是一个很好的示例,它展示了如何利用这些技术进行前后端的数据交互。下面我们将详细探讨这些知识点。 首先,`Maven`是Java项目管理工具,它...
总结来说,`@RequestBody`是Spring MVC中处理POST请求JSON数据的关键工具。它可以将JSON字符串转换为Java对象,如直接转换为String,或者转换为Map以便处理动态结构的数据。为了确保正确运行,记得在项目中包含必要...
Spring MVC中的`@ResponseBody`注解可以将方法的返回值直接转换为JSON格式发送到客户端,而`@RequestBody`则可以将请求体中的JSON数据解析成Java对象。 **Jackson** Jackson是Java中广泛使用的JSON库,它可以高效地...
本文主要介绍如何在SpringMVC中使用@RequestBody注解来接收JSON对象字符串。 首先,前端页面向服务器发送数据通常有两种格式:form格式和JSON格式。Form格式提交的数据通常由键值对组成,其格式通常为k=v&k=v,这种...
在Spring MVC中,`@RequestBody`和`@ResponseBody`两个注解是实现JSON交互的关键。`@RequestBody`注解用于读取HTTP请求的内容,通常是请求体中的JSON字符串。Spring MVC通过HttpMessageConverter接口将这个字符串...
使用`@RequestBody`和`@ResponseBody`注解,Spring MVC可以将JSON数据自动映射到Java对象。 4. **表单验证**:Spring MVC提供了一套表单验证机制,结合jQuery可以实现客户端的实时验证,提高用户体验。例如,使用...
Spring MVC 中@RequestParam 和@RequestBody 注解的使用详解 在 Spring MVC 中,@RequestParam 和@RequestBody 是两个常用的注解,用于处理前端传递来的参数。下面将详细介绍这两个注解的使用和区别。 一、@...
标题中的“Spring MVC – Easy REST-Based JSON Services with @ResponseBody”是指使用Spring MVC框架构建基于REST的JSON服务,并通过使用`@ResponseBody`注解来简化这一过程。REST(Representational State ...
在Spring MVC中,Controller的方法参数需要是`@RequestBody`注解的,这样Spring MVC会尝试将接收到的JSON数据转化为Java对象。 2. **Content-Type设置** 要使JSON数据被正确处理,必须设置HTTP请求的`Content-...
当返回类型为@RequestBody或@ResponseBody时,Spring MVC会自动将返回的对象转换为JSON,发送到客户端。 三、源代码分析 1. pom.xml:项目依赖管理文件,包含了Spring MVC、Jackson库和其他相关依赖。例如,添加...
这种方法适用于 JSON 格式的请求体,通过 `@RequestBody` 注解,Spring MVC 可以自动将请求体中的 JSON 数据转换为 Java 对象。 #### 总结 以上介绍了三种解决 Spring MVC 无法直接接收 List 类型参数的方法。这些...
本文将深入探讨Spring MVC如何支持Ajax以及相关的注解,如`@RequestBody`和`@ResponseBody`。 首先,`<mvc:annotation-driven/>`在Spring配置文件中是一个重要的元素,它告诉Spring启用注解驱动,自动注册一些关键...
4. Spring MVC 控制器处理:在Spring MVC中,可以定义一个控制器方法,该方法的参数使用@RequestBody注解,Spring MVC会自动将接收到的JSON数据映射到对应的Java对象。例如: ```java @PostMapping("/handleJson") ...
《Spring MVC Cookbook》是由PACKT Publishing在2016年出版的一本专著,主要针对Spring MVC框架提供了实用的解决方案和技巧。Spring MVC是Spring框架的一部分,它为构建基于Java的Web应用程序提供了一个模型-视图-...
在Spring MVC中集成Ajax,通常会在前端使用JavaScript库如jQuery来发送Ajax请求。例如,我们可以创建一个AJAX函数,通过`$.ajax()`或`$.getJSON()`等方法向后台发送异步请求。这些请求通常带有特定的URL和参数,对应...
在Spring MVC框架中,Ajax(Asynchronous JavaScript and XML)是一种常用的技术,用于在不刷新整个页面的情况下与服务器进行异步通信。本章将探讨如何在Spring MVC中集成和使用Ajax,以及涉及的上传和下载功能,...
总的来说,Spring MVC通过`@RequestBody`注解简化了接收JSON数据的过程,前端通过jQuery或其他JavaScript库可以方便地序列化数据为JSON格式,然后通过Ajax发送给后端。尽管相对某些框架,Spring MVC在JSON处理上可能...
弃用了struts,用spring mvc框架做了几个项目,感觉都不错,而且使用了注解方式,可以省掉一大堆配置文件。本文主要介绍使用注解方式配置的spring mvc,之前写的spring3.0 mvc和rest小例子没有介绍到数据层的内容,...
`@RequestBody`和`@ResponseBody`依赖于Spring的核心组件ConversionService,它负责将JSON字符串解析为User对象,并将User对象转换为JSON响应。 总结起来,Spring 3.x中通过JSON进行前后端数据传输主要涉及以下几个...
综上所述,"springmvc3+json参数传递后台接收json参数"涵盖了Spring MVC 3中处理JSON数据的核心概念和实践方法,包括JSON数据格式、`@RequestBody`注解、前端JSON数据封装、批量处理、错误处理和配置支持等方面的...