GET、POST编码问题

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

 

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

 

SpringMVC配置过滤器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<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配置:

1
2
3
4
5
6
7
8
<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实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
@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

posted @   欠扁的小篮子  阅读(508)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
点击右上角即可分享
微信分享提示