Servlet处理get请求时中文乱码问题

13 篇文章 0 订阅
7 篇文章 0 订阅

原文链接

我们都知道,使用Servlet处理get请求时,如果get请求的参数中有中文,直接接收会是乱码,这个时候我们使用类似下面的语句来处理乱码:

1
2
3
4
5
String name = request.getParameter("name");
System.out.prinlnt(name); // 乱码
// 处理乱码
name = new String(name.getBytes("ISO8859-1"),"UTF-8");
System.out.println(name);// 乱码问题解决

这时候每次中文都要处理,比较麻烦,我们可能会使用过滤器,使用类型下面的代码处理乱码问题:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public String getParameter(String name) {
String value = super.getParameter(name);
if (value == null)
return null;
String method = request.getMethod();
if ("get".equalsIgnoreCase(method)) {
try {
value = new String(value.getBytes("ISO8859-1"),"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return value;
}

但是,这是为什么呢?为什么我们需要将ISO8859-1转为UTF-8?为什么我们接收到的参数是ISO8859-1这种编码方式的?
其实很简单,只是个配置问题:
在tomcat安装目录下的conf/server.xml中,有如下的配置:

1
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

我们可能改动过这里的port为9999,8888等自己喜欢的端口号,这里呢,也可以设置另外一个跟上述编码问题有关的参数信息:URIEncoding,该配置决定了使用get请求通过浏览器地址栏访问tomcat时的编码方式,默认的编码方式使ISO8859-1,这一点我们可以从官网文档https://tomcat.apache.org/tomcat-7.0-doc/config/http.html) 获悉:

URIEncoding:This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. If not specified, ISO-8859-1 will be used.

知道了这点,接下来就简单了,我们可以这样配置,则上述代码中,就不需要再从ISO8859-1转为UTF-8了:

1
URIEncoding="UTF-8"

这显然比上述两种方式简单多了。

值得注意的是,从tomcat8.0开始,URIEncoding默认值不再是ISO8859-1,而变成了UTF-8 
官方文档 (https://tomcat.apache.org/tomcat-8.0-doc/config/http.html) 中是这么说的:

URIEncoding:This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. If not specified, UTF-8 will be used unless the org.apache.catalina.STRICT_SERVLET_COMPLIANCE system property is set to true in which case ISO-8859-1 will be used.

那么也就意味着,从tomcat8.0开始,get请求中的中文参数,不需要特殊处理了。而如果是tomcat8之前的项目要迁移到tomcat8上面来,则也需要特殊注意这个问题,可能要删减代码中响应乱码的处理模块了。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值