日期:2014-05-16  浏览次数:20538 次

spring mvc 返回json整合

最近要做app的服务端接口,要用json格式,就专门做了个工程,研究下spring mvc与json的整合。备忘
spring mvc返回json数据的几种方式(归纳网上做法):
1、直接 PrintWriter 输出
2、spring 内置 @ResponseBody
3、返回ModelAndView,在里面指定viewName
4、定义一个json的渲染viewResolver

我用的是第二种,比较简单,过程如下

1、准备工作 :搭个spring mvc 框架,采用 @ResponseBody方式还需要第三方jar包 (jackson,我会放在附件中)。
2、关键代码
springXX.xml

?

?

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans   
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
           http://www.springframework.org/schema/context   
           http://www.springframework.org/schema/context/spring-context-3.0.xsd
           http://www.springframework.org/schema/mvc  http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
	default-autowire="byName">
	
	<!-- 自动扫描controller bean,把作了注解的类转换为bean -->
	<context:component-scan base-package="com.demo" />

	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
	<!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver"
		p:prefix="/WEB-INF/view/" p:suffix=".jsp">
		<property name="order" value="0" />
	</bean>


	
	<mvc:annotation-driven  />
	
	<context:annotation-config />
	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
			    <ref bean="stringHttpMessageConverter" />
                <ref bean="mappingJacksonHttpMessageConverter" />
               
			</list>
		</property>
	</bean>
	<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter"> 
	
		        <property name = "supportedMediaTypes">    
                     <list>    
                         <value>text/plain;charset=UTF-8</value>    
                         <value>text/html;charset=UTF-8</value>   
                     </list>    
                </property>    
	</bean>

	<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">    
    <property name="supportedMediaTypes">    
        <list>    
            <value>application/json;charset=UTF-8</value>
             <value>text/html;charset=UTF-8</value>     
              
       </list>    
    </property>  
</bean>  

</beans>  

?controller类

?

@Controller
public class TestController {
	@RequestMapping(value = "test1.htm",method=RequestMethod.GET)
	@ResponseBody
	public String test(HttpServletResponse response) {
//此处直接返回json字符串,会乱码,未解决,只能手动设了下
		 response.setContentType("text/html;charset=UTF-8");  
	        try {
				response.getWriter().print("{code2:i33中国}");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
	        return null;  
	
	}

	@RequestMapping(value = "test2.htm")
	@ResponseBody
	public Map<String, Object> validataUser() {

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", "i am boy");
		map.put("code2", "i33werwerew是田另是l;  am boy");
		return map;
	}

	@RequestMapping(value = "test3.htm")
	@ResponseBody
	public SUser ts() {

		SUser su = new SUser();
		su.setPwd("3334右国");
		return su;
	}
}