post、get请求编码乱码

提交数据中文乱码问题:

  • post提交方式,想不乱码,只需要设置request对象的编码即可
    注意:客户机数据是以哪种编码提交的,request就应该设什么编码
    程序中设置request编码就可控制

 

request.setCharacterEncoding("UTF-8");

  • get提交方式,设置request对象的编码是无效的,用户想不乱码,只能手工转换

 

String data = "??????";//乱码字符串
byte source[]= data.getBytes("iso8859-1");//得到客户机提交的原始数据
data = new String(source,"UTF-8");//解决乱码 

等同于(开发中常用)

 

data= new String(data.getBytes("iso8859-1","UTF-8"));

  • get方式乱码,还可以通过改变服务器的配置实现

注:开发中不建议使用改服务器的方式解决乱码问题

查看tomcat7的配置文件中的*** HTTP Connector***,我们可以看到下面这些信息

AttributeDescription
URIEncodingThis specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. If not specified, ISO-8859-1 will be used.
useBodyEncodingForURIThis specifies if the encoding specified in contentType should be used for URI query parameters, instead of using the URIEncoding. This setting is present for compatibility with Tomcat 4.1.x, where the encoding specified in the contentType, or explicitly set using Request.setCharacterEncoding method was also used for the parameters from the URL. The default value is false.

注解:

URIEncoding:上面的意思是说URL编码如果未被指定,将使用默认(缺省的)ISO-8859-1 编码
useBodyEncodingForURI:useBodyEncodingForURI默认值是"false",如果修改成"true",那么程序中设置(request设置编码)何种编码方式,URL就以何种编码解码。

修改tomcat服务器的配置文件
1.打开配置文件*\tomcat\conf\server.xml
大概在70行左右会有下面的代码

 

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

方法一:修改URIEncoding(添加该属性即可)

 

<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443"  URIEncoding="UTF-8"/>

方法二:修改useBodyEncodingForURI(添加该属性即可)

 

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

程序中设置request编码就可控制

 

request.setCharacterEncoding("UTF-8");

  • 超链接方式带中文数据过来,乱码的问题解决

通过链接(html文件)传值过来比如

 

 <a href="/day06/servlet/RequestDemo6?name=中国">戳我</a>

这种传值方式是get方式

URL规定:URL地址后面如果跟了中文数据,一定要经过URL编码

html文件这样没法处理,如果这样写需要成jsp页面



作者:wswenyue
链接:https://www.jianshu.com/p/74bf04dd2599
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值