一、使用maven管理jar。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<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.5</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-lgpl</artifactId> <version>1.9.6</version> </dependency> |
二、配置spring-servlet.xml:
1 2 3 4 5 6 7 |
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list > <ref bean="mappingJacksonHttpMessageConverter" /> </list> </property> </bean> |
mappingJacksonHttpMessageConverter : 用来处理json格式转换
1 2 3 4 5 6 7 |
<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 可以 直接写成如下:
1 |
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /> |
这样默认应该是 :ISO-88859-1
2、supportedMediaTypes 的 list 里面 可以写多个value
1 2 3 4 5 6 7 |
<list> <value>apolication/json; charset=UTF-8</value> <value>text/html;charset=UTF-8</value> </list> |
三、controller 配置@ResponseBody
1 2 3 4 5 6 7 8 9 10 11 |
@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; } } |
四:页面上仍然按照原来的ajax区json的格式一样、
题外话: 关于 @ResponseBody:将内容或对象作为 HTTP 响应正文返回,使用@ResponseBody将会跳过视图处理部分,而是调用适合HttpMessageConverter,将返回值写入输出流。