mvc json
SpringMVC 提供了处理 JSON 格式请求 / 响应的 HttpMessageConverter:MappingJackson2HttpMessageConverter。利用 Jackson 开源类包处理 JSON 格式的请求或响应消息。
我们需要做的:
org.springframework.web.bind.annotation.RequestBody 注解用于读取 Request 请求的 body 部分数据,使用系统默认配置的 HttpMessageConverter 进行解析,然后把响应的数据绑定到 Controller 中的方法的参数上。
数据编码格式由请求头的 ContentType 指定。它分为以下几种情况:
1.application/x-www-form-urlencoded,[email protected]@ModelAttribute 也可以处理,并且很方便,[email protected]
2.multipart/form-data,@RequestBody 不能处理这种数据格式的数据。
3.application/json、application/xml 等格式的数据,[email protected]
[email protected]�JSON 格式的数据,并将其转换为对应的数据类型。
DEMO: 接收 JSON 格式的数据:
1.index.jsp
testRequestBody 函数发送异步请求到 "json/testRequestBody", 其中:contentType:"application/json" 表示发送的内容编码格式为 json 格式,data:JSON.stringify(....) 表示发送一个 json 数据;请求成功后返回一个 json 数据,接收到返回的 json 数据后将其设置到 span 标签中
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>测试json格式的数据</title>
- <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
- <script type="text/javascript" src="js/json2.js"></script>
- <script type="text/javascript">
- $(document).ready(function(){
- testRequestBody();
- });
- function testRequestBody(){
- $.ajax(
- {
- url:"${pageContext.request.contextPath}/json/testRequestBody",
- dateType:"json",
- type:"post",
- contentType:"application/json",
- data:JSON.stringify({id:1,name:"老人与海"}),
- async:true,
- success:function(data){
- alert("成功");
- alert(data);
- console.log(data);
- $("#id").html(data.id);
- $("#name").html(data.name);
- $("#author").html(data.author);
- },
- error:function(){
- alert("数据发送失败!");
- }
- });
- }
- </script>
- </head>
- <body>
- 编号:<span id="id"></span>
- 书名:<span id="name"></span>
- 作者:<span id="author"></span>
- </body>
- </html>
2.Book 实体类
- package com.cn.domain;
- import java.io.Serializable;
- public class Book implements Serializable {
- private Integer id;
- private String name;
- private String author;
- public Book(){
- super();
- }
- public Book(Integer id, String name, String author) {
- super();
- this.id = id;
- this.name = name;
- this.author = author;
- }
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getAuthor() {
- return author;
- }
- public void setAuthor(String author) {
- this.author = author;
- }
- }
3.BookController
[email protected] Book book,[email protected],[email protected] 参数是 HttpServletResponse 对象,用来输出响应数据到客户端。
- package com.cn.controller;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.RequestMapping;
- import com.cn.domain.Book;
- import com.fasterxml.jackson.databind.ObjectMapper;
- @Controller
- @RequestMapping("/json")
- public class BookController {
- private static final Log logger = LogFactory.getLog(BookController.class);
- @RequestMapping(value="/testRequestBody")
- public void setJson(@RequestBody Book book, HttpServletResponse response) throws Exception{
- //注意ObjectMapper类是Jackson库的主要类。负责将java对象转换成json格式的数据。
- ObjectMapper mapper = new ObjectMapper();
- logger.info(mapper.writeValueAsString(book));
- book.setAuthor("海明威");
- response.setContentType("application/json;charset=UTF-8");
- response.getWriter().println(mapper.writeValueAsString(book));
- }
- }
4.springmvc-config
(1) 会自动注册 RequestMappingHandlerMapping 与 RequestMappingHandlerAdapter 两个 Bean,[email protected],[email protected]@[email protected][email protected]JSON 功能的支持。
(2)<mvc:default-servlet-handler/> 使用默认的 Servlet 来响应静态文件,因为在 web.xml 中使用了 DispatcherServlet 截获所有请求的 url,而本例引入的 js/jquery-1.11.0.min.js 以及 js/json2.js 文件的时候,DispatcherServlet 会将 "/" 看成请求路径,就会报 404 的错误。而当配置文件加上这个默认的 Servlet 时,Servlet 在找不到它时会去找静态的内容。
- <?xml version="1.0" encoding="UTF-8" ?>
- <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"
- xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-4.2.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
- ">
- <!-- Spring 可以自动去扫描base-pack下面的包或者子包下面的java文件 -->
- <!-- 如果扫描到spring相关的注解类,将其注册为spring的bean -->
- <context:component-scan base-package="com.cn.controller" />
- <!-- 设置配置方案 -->
- <mvc:annotation-driven/>
- <mvc:default-servlet-handler/>
- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"
- />
- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"
- />
- <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="prefix">
- <value>
- /WEB-INF/content/
- </value>
- </property>
- <property name="suffix">
- <value>
- .jsp
- </value>
- </property>
- </bean>
- </beans>
需要添加的 jar 包:Spring 的所有 jar、commons-logging.jar 以及 Jackson 相关的 jar
需要引入的 js:jquery.js、json2.js
源代码:http://down.51cto.com/data/2300368
来源: http://www.bubuko.com/infodetail-2032365.html