读书人

spring mvc 回来json整合

发布时间: 2012-12-27 10:17:10 作者: rapoo

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/><!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 --><beanp:suffix=".jsp"><property name="order" value="0" /></bean><mvc:annotation-driven  /><context:annotation-config /><bean/>                <ref bean="mappingJacksonHttpMessageConverter" />               </list></property></bean><bean id="stringHttpMessageConverter" name="code">@Controllerpublic class TestController {@RequestMapping(value = "test1.htm",method=RequestMethod.GET)@ResponseBodypublic 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 blocke.printStackTrace();}          return null;  }@RequestMapping(value = "test2.htm")@ResponseBodypublic 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")@ResponseBodypublic SUser ts() {SUser su = new SUser();su.setPwd("3334右国");return su;}}

读书人网 >JavaScript

热点推荐