以前项目中也遇到过返回JSON时乱码问题,当时找到了一个方法解决了问题可是没有明白缘由,今天这个项目又遇到了JSON乱码问题,用以前的方法不行,看了这篇博文才明白为何html
@RequestMapping(value = "testPersonalValidtor.do",produces = "application/json;charset=utf-8")
在方法上加上这个注解就能够了。可是这样写的话有限制,只能在特定的方法上面使用。若是须要全局都使用的话,须要修改SpringMVC的配置文件。java
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" > <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /> <bean 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> </list> </property> </bean>
而且须要在Maven依赖中配置上Jackjson的依赖。
<dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.9.13</version> </dependency>
<!-- SpringMVC注解驱动 --> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/> <bean 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> </mvc:message-converters> </mvc:annotation-driven>
注意:始用这种配置的时候,须要去掉RequestMappingHandlerMapping、RequestMappingHandlerAdapter或者DefaultAnnotationHandlerMapping、AnnotationMethodHandlerAdapter的Bean配置,要否则可能会不生效。
@RequestMapping(value = "testPersonalValidtor.do") @ResponseBody //直接返回对象 public Object testPersonalValidtor(@Valid PersonScope personScope, BindingResult bindingResult){ if(bindingResult.hasErrors()){ StringBuffer sb = new StringBuffer(); for(ObjectError objectError : bindingResult.getAllErrors()){ sb.append(((FieldError)objectError).getField() +" : ").append(objectError.getDefaultMessage()); } return sb.toString(); }else{ return personScope; } }
参考连接:https://blog.csdn.net/porsche_gt3rs/article/details/79062704