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.其他类似
原文地址:https://www.cnblogs.com/menbo/p/10310945.html
时间: 2024-11-08 20:46:07