request和response的setCharacterEncoding()方法

1、pageEncoding=”UTF-8”的作用是设置JSP编译成Servlet时使用的编码。
2、contentType=”text/html;charset=UTF-8”的作用是指定服务器响应给浏览器的编码。

3、request.setCharacterEncoding(“UTF-8”)的作用是设置对客户端请求和数据库取值时的编码,不指定的话使用iso-8859-1。(只解决POST乱码)

4、response.setCharacterEncoding(“UTF-8”)的作用是指定服务器响应给浏览器的编码。

5、response.setContentType(“text/html;charset=utf-8”)的作用是指定服务器响应给浏览器的编码。同时,浏览器也是根据这个参数来对其接收到的数据进行重新编码(或者称为解码)。

6、tomcat 8 已经将get方式乱码问题解决了

 

对于发送数据,服务器按照response.setCharacterEncoding—contentType—pageEncoding的优先顺序,对要发送的数据进行编码。

Get是URL解码方式。默认解码格式是Tomcat8编码格式。所以URL解码是UTF-8,覆盖掉了request容器解码格式

Post是实体内容解码方式。默认解码格式是request编码格式。与Tomcat8编码格式无关

tomcat服务器中Response容器默认以ISO8859-1的编码解析数据,因此如果需要在参数中解析中文,需要设置

request.setCharacterEncoding(“utf-8”);

post得到前台数据:(request容器默认是gbk格式)
request.setCharacterEncoding(“utf-8”);
System.out.println(request.getParameter(“name”));

GET得到前台数据:(不需要设置编码格式,默认是按照tomcat服务器的编码格式)
System.out.println(request.getParameter(“name”));

GET POST给前台传数据
response.setCharacterEncoding(“utf-8”);
response.getWriter().write(“我爱你”);

posted @ 2020-02-28 12:06  骑着蜗牛一起狂奔  阅读(637)  评论(0)    收藏  举报