tomcat的编码设置

D:\Tomcat\apache-tomcat-9.0.0.M15\conf\server.xml


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


特别引起我注意的是 URIEncoding="UTF-8" ,如果不设置,url上传递的中文(get请求)就不能被正确解码。

提醒各位使用utf-8编码的朋友注意使用tomcat的这个设置。

Tomcat 8及以后URIEncoding默认为"UTF-8",所以就不用设置了。


也可以如下设置:

useBodyEncodingForURI,就在获取请求参数前使用request.setCharacterEncoding来解决乱码。

<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443"
			   useBodyEncodingForURI="true"
	 />
@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置响应内容格式
        response.setContentType("text/html;charset=utf-8");
        //取得输出对象
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>get</title>");
        out.println("</head>");
        out.println("<body>");
        //取得请求参数
        request.setCharacterEncoding("UTF-8");
        String name = request.getParameter("name");
        //name = new String(name.getBytes("ISO-8859-1"), "UTF-8");
        out.println("</body>");
        out.println("<h1>您的姓名是:" + name + "</h1>");
        out.println("</html>");
        out.close();
    }

对于post方式

request.setCharacterEncoding("UTF-8");


URIEncoding与useBodyEncodingForURI 在tomcat中文乱码处理上的区别


大家知道tomcat5.0开始,对网页的中文字符的post或者get,经常会出现乱码现象。

具体是因为Tomcat默认是按ISO-8859-1进行URL解码,ISO-8859-1并未包括中文字符,这样的话中文字符肯定就不能被正确解析了。

常见的解决方法是在tomcat的server.xml下的connetor属性中增加URIEncoding或者useBodyEncodingForURI属性。

但是,这两种方式有什么区别呢?

我简单谈一下自己的理解:

按照tomcat-docs/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. 

useBodyEncodingForURI:This specifies if the encoding specified in contentType should be used for URI query parameters, instead of using the URIEncoding.

 

也就是说,

 useBodyEncodingForURI参数表示是否用request.setCharacterEncoding 
参数对URL提交的数据和表单中GET方式提交的数据进行重新编码,在默认情况下,该参数为false。

URIEncoding参数指定对所有GET方式请求进行统一的重新编码(解码)的编码。

 

URIEncoding和useBodyEncodingForURI区别是,

URIEncoding是对所有GET方式的请求的数据进行统一的重新编码,

而useBodyEncodingForURI则是根据响应该请求的页面的request.setCharacterEncoding参数对数据进行的重新编码,不同的页面可以有不同的重新编码的编码


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

N3verL4nd

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值