SpringMVC整合fastjson-1.1.41

完整版見https://jadyer.github.io/2014/08/06/springmvc-fastjson/




以前用fastjson也只是硬編碼,就好像這篇博文寫的http://blog.csdn.net/jadyer/article/details/24395015

昨天心血來潮突然想和SpringMVC整合,然後利用@ResponseBody註解的方式序列化輸出json字符串

下面是研究成果

 

首先是applicationContext.xml中的相關配置

<?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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
						http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
						http://www.springframework.org/schema/mvc
						http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
						http://www.springframework.org/schema/context
						http://www.springframework.org/schema/context/spring-context-3.2.xsd">
	<context:component-scan base-package="com.jadyer"/>
	
	<mvc:annotation-driven>
		<mvc:message-converters register-defaults="true">
			<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
				<property name="supportedMediaTypes" value="text/html;charset=UTF-8"/>
				<property name="features">
					<array>
						<value>WriteMapNullValue</value>
						<value>WriteNullStringAsEmpty</value>
					</array>
				</property>
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>
	
	<!-- fastjson-1.1.41與SpringMVC整合 -->
	<!-- 
	1)若按照jackson和SpringMVC的整合方式,應按照下面的寫法,但測試發現這樣會報告"HTTP Status 406"
	  The resource identified by this request is only capable of generating responses
	  with characteristics not acceptable according to the request "accept" headers.
	2)測試通過的整合方式爲上面那樣在mvc:annotation-driven裏面進行註冊
	3)supportedMediaTypes增加[text/html;charset=UTF-8]值,是爲了兼容IE6
	  否則[application/json]值在IE6中會導致彈出對話框詢問是否保存文件,而firefox等高級瀏覽器會正常打印json字符串
	4)若像下面這樣給supportedMediaTypes屬性賦兩個值[text/html;charset=UTF-8]和[application/json],則[application/json]是無效的
	  因爲此時應答給瀏覽器(或者說請求方)的Content-Type頭信息都是[text/html;charset=UTF-8],所以給它一個值就行了
	  如果給supportedMediaTypes的值爲[application/json],則應答給瀏覽器的Content-Type頭信息就是[application/json;charset=UTF-8]
	5)關於features屬性,不是serializerFeature,而是features,詳見FastJsonHttpMessageConverter.java
	  它是用來控制json序列化輸出時的一些額外屬性,比如說該字段是否輸出、輸出時key使用單引號還是雙引號、key不使用任何引號等等
	  QuoteFieldNames----------輸出key時是否使用雙引號,默認爲true
	  WriteMapNullValue--------是否輸出值爲null的字段,默認爲false
	  WriteNullNumberAsZero----數值字段如果爲null,輸出爲0,而非null
	  WriteNullListAsEmpty-----List字段如果爲null,輸出爲[],而非null
	  WriteNullStringAsEmpty---字符類型字段如果爲null,輸出爲"",而非null
	  WriteNullBooleanAsFalse--Boolean字段如果爲null,輸出爲false,而非null
	6)通常在網上搜到的fastjson和springMVC整合的例子中都像下面註釋的代碼那樣給了兩個屬性WriteMapNullValue和QuoteFieldNames
	  這就表示爲json解析器設置QuoteFieldNames和WriteMapNullValue的值爲true,即輸出時key使用雙引號,同時也輸出值爲null的字段
	7)輸出時某字段爲String類型,且值爲null,此時若需要其輸出,且輸出值爲空字符串,則需同時賦值WriteMapNullValue和WriteNullStringAsEmpty
	  經測試,若只賦值WriteNullStringAsEmpty,則不會輸出該字段..加上WriteMapNullValue屬性後,便輸出了,且輸出值不是null,而是預期的空字符串
	 -->
	<!-- 
	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
					<property name="supportedMediaTypes">
						<list>
							<value>text/html;charset=UTF-8</value>
							<value>application/json</value>
						</list>
					</property>
					<property name="serializerFeature">
						<array>
							<value>QuoteFieldNames</value>
							<value>WriteMapNullValue</value>
						</array>
					</property>
				</bean>
			</list>
		</property>
	</bean>
	 -->
	<!-- 
	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
					<property name="supportedMediaTypes" value="text/html;charset=UTF-8"/>
				</bean>
			</list>
		</property>
	</bean>
	 -->
</beans>

接着是SpringMVC中的Controller

package com.jadyer.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.jadyer.model.LoginResult;

@Controller
@RequestMapping(value="/account")
public class AccountController {
	@Resource
	private AccountService accountService;
	
//	@RequestMapping(value="/login")
//	public String login(String username, String password, HttpServletResponse response) throws IOException{
//		response.setContentType("text/plain; charset=UTF-8");
//		response.setHeader("Cache-Control", "no-cache");
//		response.setHeader("Pragma", "no-cache");
//		response.setDateHeader("Expires", 0);
//		PrintWriter out = response.getWriter();
//		out.write(JSON.toJSONString(accountService.login(username, password)));
//		out.flush();
//		out.close();
//		return null;
//	}
	@ResponseBody
	@RequestMapping(value="/login")
	public LoginResult login(String username, String password){
		LoginResult result = new LoginResult();
		//驗簽過程暫略....
		result = accountService.login(username, password);
		return result;
	}
}


最後是login()方法的應答實體類LoginResult.java

package com.jadyer.model;

public class LoginResult {
	private String respCode; //應答碼
	private String respDesc; //應答描述
	private String userId;   //用戶編號
	private String username; //用戶名
	private String mobileNo; //用戶手機號
	private String integral; //用戶擁有的積分
	/*-- 對應的setter和getter略 --*/
}
發佈了360 篇原創文章 · 獲贊 338 · 訪問量 121萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章