首页 > 代码库 > SpringMVC整合fastjson-1.1.41

SpringMVC整合fastjson-1.1.41

以前用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=http://www.mamicode.com/"text/html;charset=UTF-8"/>>
接着是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=http://www.mamicode.com/"/account")>


最后是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略 --*/
}