Spring MVC form表单post提交出现乱码

时间:2022-08-26 13:04:40

转自:https://blog.csdn.net/yifansj/article/details/63008780

主要原因是:页面提交时,使用<contentType:utf-8/>格式,而服务端HttpMessageConverter解码时使用其它格式解码(如:ISO-8859-1)导致

解决方案:在Servlet中设置CharacterEncoding为UTF-8格式。

方法一:在Web.xml中加入Spring的字符集过滤器(已测)

[java] view plain copy
  1. <filter>  
  2.     <filter-name>characterEncodingFilter</filter-name>  
  3.     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  4.     <init-param>  
  5.         <param-name>encoding</param-name><span style="white-space:pre;">    </span>  
  6.         <param-value>UTF-8</param-value>  
  7.     </init-param>  
  8.     <init-param>  
  9.         <param-name>forceEncoding</param-name><span style="white-space:pre;">   </span>  
  10.         <param-value>true</param-value>  
  11.     </init-param>  
  12. </filter>  
encoding

字符集,将request字符集设置成encoding指定格式(相当于request.setCharacterEncoding)

forceEncoding

强制字符集设置,主要用来设置response字符集是否也是encoding指定格式

当设置为true时,相当于request.setCharacterEncoding + response.setCharacterEncoding

当设置为false时(默认),相当于request.setCharacterEncoding

加入后相当于在servlet中加入下面代码

[java] view plain copy
  1. request.setCharacterEncoding("UTF-8");    
  2. response.setCharacterEncoding("UTF-8");    

方法二:手动写Filter(未测)

对每个访问进行拦截,并执行下列代码

[java] view plain copy
  1. request.setCharacterEncoding("UTF-8");    
  2. response.setCharacterEncoding("UTF-8");    

方法三:设置HttpMessageConverter实现类的解码方式(未测试)

[java] view plain copy
  1. <mvc:annotation-driven>    
  2.     <mvc:message-converters>    
  3.         <bean class="org.springframework.http.converter.StringHttpMessageConverter">    
  4.             <property name="supportedMediaTypes">    
  5.                 <list>    
  6.                     <value>text/plain;charset=UTF-8</value>    
  7.                     <value>text/html;charset=UTF-8</value>    
  8.                 </list>    
  9.             </property>    
  10.         </bean>    
  11.         <bean    
  12.             class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">    
  13.             <property name="supportedMediaTypes">    
  14.                 <list>    
  15.                     <value>application/json; charset=UTF-8</value>    
  16.                     <value>application/x-www-form-urlencoded; charset=UTF-8</value>    
  17.                 </list>    
  18.             </property>    
  19.         </bean>    
  20.     </mvc:message-converters>    
  21. </mvc:annotation-driven>