js里通过ajax调用springmvc,后台返回的中文字符串乱码,通过搜索找解决方,大都让配置StringHttpMessageConverter这个bean来纠正编码问题,但是我用之后死活不生效,无奈跟踪代码,发现一次请求中根本就没有调用到org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter这个bean,那么按照网上配置的方法肯定是不起作用的。一步一步跟踪代码,发现到org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter这个类的时候有一个setMessageConverters方法,并且发现convert就是在这个类里面被注入的,但是网上很多配置都是org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter这个类,这样当然不行了,因为就没有用到这个类,于是搜索RequestMappingHandlerAdapter这个类,终于找到了原因,原来是因为annotation-driven缺省注册类的改变。
Spring 3.0.x中使用了annotation-driven后,缺省使用DefaultAnnotationHandlerMapping 来注册handler method和request的mapping关系。 AnnotationMethodHandlerAdapter来在实际调用handlermethod前对其参数进行处理。 而在spring mvc 3.1中,对应变更为
DefaultAnnotationHandlerMapping -> RequestMappingHandlerMapping
AnnotationMethodHandlerAdapter -> RequestMappingHandlerAdapter
AnnotationMethodHandlerExceptionResolver -> ExceptionHandlerExceptionResolver
解决方案自然就有了,将配置变更为
<mvc:annotation-driven> <mvc:message-converters> <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> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json; charset=UTF-8</value> <value>application/x-www-form-urlencoded; charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
当然,这是其中一个解决方案,还可以用另一种方法, 就是在@RequestMapping里面加入produces = “text/plain;charset=UTF-8” ,如下:
@RequestMapping(value = "/test", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
这里的charset将会覆盖默认的ISO-8859-1,到此,问题解决!
在东北,这两天还能出来跟你见面的,就已经可以算的上是生死之交了。因为。。。太!特!么!冷!了!跟你出来玩,就已经将生死置之度外了。。
哥们你太给力了 😉