一、使用maven管理jar。
- <dependency>
- <span style="white-space:pre"> </span><groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-core-lgpl</artifactId>
- <version>1.9.6</version>
- </dependency>
- <dependency>
- <span style="white-space:pre"> </span><groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-core-asl</artifactId>
- <version>1.9.4</version>
- </dependency>
- <dependency>
- <span style="white-space:pre"> </span><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>
- <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" />
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;
- }
- }
四:页面上仍然按照原来的ajax区json的格式一样、
题外话:
关于 @ResponseBody:
将内容或对象作为 HTTP 响应正文返回,使用@ResponseBody将会跳过视图处理部分,而是调用适合HttpMessageConverter,将返回值写入输出流。