1. 搭建 SpringMVC+spring 环境
2. 配置 web.xml 以及 springmvc-config.xml,Web.xml 同 Spring 使用 jackson 处理 JSON 数据一样, Springmvc-config.xml 有些许差别. Spring 默认配置使用 Jackson, 如果要使用 fastjson 则需要配置 HttpMessageConverter.
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xmlns:util="http://www.springframework.org/schema/util"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-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/util
- http://www.springframework.org/schema/util/spring-util-4.2.xsd">
- <!-- spring 可以自动去扫描 base-pack 下面的包或者子包下面的 java 文件,
- 如果扫描到有 Spring 的相关注解的类, 则把这些类注册为 Spring 的 bean -->
- <context:component-scan base-package="com.moon.controller"/>
- <!-- 使用默认的 Servlet 来响应静态文件 -->
- <mvc:default-servlet-handler/>
- <!-- 设置配置方案 -->
- <mvc:annotation-driven>
- <!-- 设置不使用默认的消息转换器 -->
- <mvc:message-converters register-defaults="false">
- <!-- 配置 Spring 的转换器 -->
- <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
- <bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"/>
- <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
- <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
- <!-- 配置 fastjson 中实现 HttpMessageConverter 接口的转换器 -->
- <bean id="fastJsonHttpMessageConverter"
- class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
- <!-- 加入支持的媒体类型: 返回 contentType -->
- <property name="supportedMediaTypes">
- <list>
- <!-- 这里顺序不能反, 一定先写 text/html, 不然 ie 下会出现下载提示 -->
- <value>text/HTML;charset=UTF-8</value>
- <value>application/JSON;charset=UTF-8</value>
- </list>
- </property>
- </bean>
- </mvc:message-converters>
- </mvc:annotation-driven>
- <!-- 视图解析器 -->
- <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>
3.Controller 层
- import com.alibaba.fastjson.JSONObject;
- import com.moon.domain.Book;
- @Controller
- public class BookController {
- @RequestMapping(value="/json")
- public void test(@RequestBody Book book,HttpServletResponse response)throws Exception{
- book.setAuthor("jackson");
- response.setContentType("text/html;charset=UTF-8");
- response.getWriter().println(JSONObject.toJSONString(book));
- }
- }
4. 其他类似
来源: http://www.bubuko.com/infodetail-2931433.html