我是程序员;您好程先生;叫我序员就好了

get、post方式传送数据的乱码问题解决方案

2014-10-10  本文已影响963人  wswenyue

get/post方式的编码问题解决方案


提交数据中文乱码问题:

request.setCharacterEncoding("UTF-8");

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

等同于(开发中常用)

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

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

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

Attribute Description
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.
useBodyEncodingForURI This 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页面

上一篇 下一篇

猜你喜欢

热点阅读