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

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

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

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

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

[java] view plain copy
  1.   
  2.     characterEncodingFilter  
  3.     class>org.springframework.web.filter.CharacterEncodingFilterclass>  
  4.       
  5.         encoding"white-space:pre;">      
  6.         UTF-8  
  7.       
  8.       
  9.         forceEncoding"white-space:pre;">     
  10.         true  
  11.       
  12.   
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.     
  2.         
  3.         class="org.springframework.http.converter.StringHttpMessageConverter">    
  4.             "supportedMediaTypes">    
  5.                     
  6.                     text/plain;charset=UTF-8    
  7.                     text/html;charset=UTF-8    
  8.                     
  9.                 
  10.             
  11.         
  12.             class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">    
  13.             "supportedMediaTypes">    
  14.                     
  15.                     application/json; charset=UTF-8    
  16.                     application/x-www-form-urlencoded; charset=UTF-8    
  17.                     
  18.                 
  19.             
  20.         
  21.     



你可能感兴趣的:(Spring MVC form表单post提交出现乱码)