通常我们会设置request.setCharacterEncoding("utf-8"),response.setCharacterEncoding("utf-8")这两个方法来防止页面乱码。但会发现,有些情况下,post请求提交的数据的确没有乱码了,而get请求提交的数据还是乱码。


为了解决这个问题,我们需要到Tomcat根目录的conf/service.xml中配置两个参数: URIEncoding="UTF-8"和 useBodyEncodingForURI="true"

get请求编码格式 java get请求乱码_乱码


下面解释为什么要设置这两个参数


先看看官方文档的注释

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是指定服务器这边读取URI(注意不是URL)时的编码格式,默认为iso-8859-1

useBodyEncodingForURI是指定读取URIquery parameters(查询参数)时的编码格式,当设置为true时,编码与Request.setCharacterEncoding方法设置的相同,即跟请求体编码一致。


URI和query parmaters在URL中的对应部分如下

get请求编码格式 java get请求乱码_服务器_02


下面举一个例子

IE浏览器默认的URI编码是UTF-8,query paramters的编码是GBK


创建一个servlet类

@webservlet("/测试")
public class AServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		
		String params=req.getParameter("name");
		System.out.println(params);
	
	}
}




1.Tomcat根目录的conf/service.xml没有配置对应参数

结果:访问失败

原因:IE浏览器这边将含有中文的URI用“UTF-8”编码成二进制后发到服务器,服务器用默认的“ISO-8859-1”解码失败,无法比对,所以访 问失败


2.Tomcat根目录的conf/service.xml中设置URIEncoding="GBK"

结果:访问失败

原因:IE浏览器这边将含有中文的URI用“UTF-8”编码成二进制后发到服务器,服务器用默认的“GBK”解码失败,无法比对,所以访问失败


3.Tomcat根目录的conf/service.xml中设置URIEncoding="UTF-8"

结果:访问成功,服务器这端输出 ??

原因:URI成功解码,但query paramters在浏览器编码是GBK,在服务器这端解码不一样


4.Tomcat根目录的conf/service.xml中设置URIEncoding="UTF-8"useBodyEncodingForURI="true"

结果:访问成功,服务器这端输出 ??

原因:URI成功解码,query paramters在浏览器编码是GBK,在服务器这端解码与请求体相同,都为"UTF-8",解码失败。


5.Tomcat根目录的conf/service.xml中设置URIEncoding="UTF-8"useBodyEncodingForURI="true"。servlet中改为req.setCharacterEncoding("GBK");

结果:访问成功,服务器这端输出‘啊’

原因:URI成功解码,query paramters在浏览器编码是GBK,在服务器这端解码与请求体相同,都为"GBK",解码成功。


至此,关于get请求为什么要在tomcat的service.xml配置两个参数的原因想必完全清楚了吧~~