一、使用maven管理jar。
- <dependency>
- <groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-core-lgpl</artifactId>
- <version>1.9.6</version>
- </dependency>
- <dependency>
- <groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-core-asl</artifactId>
- <version>1.9.4</version>
- </dependency>
- <dependency>
- <groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-mapper-asl</artifactId>
- <version>1.9.9</version>
- </dependency>
- <dependency>
- <groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-mapper-lgpl</artifactId>
- <version>1.9.6</version>
- </dependency>
二、配置spring-servlet.xml:
- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
- <property name="messageConverters">
- <list >
- <ref bean="mappingJacksonHttpMessageConverter" />
- </list>
- </property>
- </bean>
mappingJacksonHttpMessageConverter : 用来处理json格式转换
- <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
- <property name="supportedMediaTypes">
- <list>
- <value>application/json;charset=UTF-8</value>
- </list>
- </property>
- </bean>
1、
如果 mappingJacksonHttpMessageConverter 可以 直接写成如下:
- <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
这样默认应该是 :ISO-88859-1
2、
supportedMediaTypes 的 list 里面 可以写多个value
<list>
<value>apolication/json; charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
三、controller 配置@ResponseBody
- @Controller
- public class LoginController {
- @RequestMapping(value="/validataUser.json")
- @ResponseBody
- public Map<String,Object> validataUser(@RequestParam String userName){
- logger.info(" validata user : {}",userName);
- Map<String,Object> map = new HashMap<String,Object>();
- map.put("code", true);
- return map;
- }
- }
- //可以从后台获取对象、List、Map在前台显示
四:页面上仍然按照原来的ajax区json的格式一样、
//注意对返回json取数据时样式书写,有的里面嵌套数组
题外话:
关于 @ResponseBody:
将内容或对象作为 HTTP 响应正文返回,使用@ResponseBody将会跳过视图处理部分,而是调用适合HttpMessageConverter,将返回值写入输出流。