转自:https://blog.csdn.net/yifansj/article/details/63008780
主要原因是:页面提交时,使用<contentType:utf-8/>格式,而服务端HttpMessageConverter解码时使用其它格式解码(如:ISO-8859-1)导致
解决方案:在Servlet中设置CharacterEncoding为UTF-8格式。
方法一:在Web.xml中加入Spring的字符集过滤器(已测)
- <filter>
- <filter-name>characterEncodingFilter</filter-name>
- <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
- <init-param>
- <param-name>encoding</param-name><span style="white-space:pre;"> </span>
- <param-value>UTF-8</param-value>
- </init-param>
- <init-param>
- <param-name>forceEncoding</param-name><span style="white-space:pre;"> </span>
- <param-value>true</param-value>
- </init-param>
- </filter>
字符集,将request字符集设置成encoding指定格式(相当于request.setCharacterEncoding)
forceEncoding
强制字符集设置,主要用来设置response字符集是否也是encoding指定格式
当设置为true时,相当于request.setCharacterEncoding + response.setCharacterEncoding
当设置为false时(默认),相当于request.setCharacterEncoding
加入后相当于在servlet中加入下面代码
- request.setCharacterEncoding("UTF-8");
- response.setCharacterEncoding("UTF-8");
方法二:手动写Filter(未测)
对每个访问进行拦截,并执行下列代码
- request.setCharacterEncoding("UTF-8");
- response.setCharacterEncoding("UTF-8");
方法三:设置HttpMessageConverter实现类的解码方式(未测试)
- <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>