GET、POST编码问题

GET请求、POST经常会出现中文乱码的问题,最好约定前后端的编码,一般为UTF-8。但是这里面也是有坑的。

后端设置编码为UTF-8的推荐方式:

SpringMVC配置过滤器:

<filter>  
    <filter-name>characterEncodingFilter</filter-name>  
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
    <init-param>  
        <param-name>encoding</param-name>  
        <param-value>UTF-8</param-value>  
    </init-param>  
    <init-param>  
        <param-name>forceEncoding</param-name>  
        <param-value>true</param-value>  
    </init-param>  
</filter>  
<filter-mapping>  
    <filter-name>characterEncodingFilter</filter-name>  
    <url-pattern>/*</url-pattern>  
</filter-mapping> 

  

此配置可以将请求体的内容按照UTF-8编码解码。

Tomcat的server.xml配置:

<Connector port="8080" protocol="HTTP/1.1"  
               maxThreads="200" connectionTimeout="20000"  
               enableLookups="false" compression="on"  
               redirectPort="8443"  
               URIEncoding="UTF-8"  
   
               compressableMimeType="text/html,text/xml,text/plain,text/javascript,application/json"  
/> 

  

URIEncoding可以配置url中的编码,防止get请求参数中文乱码。这里还可以加一个参数,useBodyEncodingForURI。useBodyEncodingForURI=true时,代表url中请求参数的编码方式要采用请求体的编码方式。

这两个都配上,基本上就可以保证从前端传来的utf-8编码的请求到后端不会乱码了。

这里的一个坑是,对于Tomcat来说,URIEncoding就是针对url中的请求参数的编码设置的,而代码中的request.setCharacterEncoding('UTF-8')或者http报文请求头中的content-type中的编码都是针对请求体的。所以说如果只配了SpringMVC的过滤器却没有配置server.xml,就很可能会出现get请求中文乱码的问题。

配上SpringMVC的编码过滤器后,server.xml中的URIEncoding和useBodyEncodingForURI可以任选一种或者两个都配上,保证不会出现中文乱码。

事实上Tomcat8.0之后server.xml中的默认URIEncoding就是UTF-8。官方文档中建议使用第一种URIEncoding的方式。第二种配置方式主要为了兼容 Tomcat 4.1.x之前的版本。

题外话,可以看一下Spring的CharacterEncodingFilter实现:

@Override  
protected void doFilterInternal(  
      HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)  
      throws ServletException, IOException {  
   
   if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {  
      request.setCharacterEncoding(this.encoding);  
      if (this.forceEncoding) {  
         response.setCharacterEncoding(this.encoding);  
      }  
   }  
   filterChain.doFilter(request, response);  
}

  

可以看出,是通过setCharacterEncoding解决编码问题的,其作用与设置Content-Type等效。因此只能解决请求体的编码。

参考文章

https://blog.csdn.net/x_iya/article/details/78636733

http://www.cnblogs.com/panxuejun/p/6837677.html

https://blog.csdn.net/hqfhello/article/details/51496955

https://www.cnblogs.com/yoyotl/p/5390876.html

猜你喜欢

转载自www.cnblogs.com/z941030/p/9223526.html