以前項目中也遇到過返回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