1. 程式人生 > >Spring使用fastjson處理json數據

Spring使用fastjson處理json數據

xmlns public 接口 視圖解析 servle oca ati com framework

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.其他類似

Spring使用fastjson處理json數據