编码
常见的字符编码:iso-8859-1(不支持中文)、gb2312、gbk、gb18030(中国的国标码)、utf-8(万国码)
1、响应编码
见图响应编码.jpg
2、案例:演示请求编码
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*
* 1.先获取到iso的错误字符串 2.回退,使用utf-8重编
*/
String name = request.getParameter("username");
byte[] bytes = name.getBytes("iso-8859-1");
name = new String(bytes,"utf-8");
System.out.println(name);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 在获取参数前先使用request.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
String name = request.getParameter("username");
System.out.println(name);
}
3、URL编码
表单的类型:Content-Type:application/x-www-form-urlencoded,就是把中文转换成%后面跟随两位的16进制
为什么要用它?
在客户端和服务器之间传递中文是需要把它转换成网络适合的方式。
@Test
public void fun1() throws IOException {
String name = "李四";
byte[] bytes = name.getBytes("utf-8");
System.out.println(Arrays.toString(bytes));
// [-26, -99, -114, -27, -87, -119, -27, -87, -73]
// 得到的数组小于的需要+255,再转换成16进制,前面再加%
String s = URLEncoder.encode(name, "utf-8");
// %E6%9D%8E%E5%A9%89%E5%A9%B7
System.out.println(s);
s = URLDecoder.decode(s, "utf-8");
System.out.println(s);
}
响应编码
GET请求编码
POST请求编码
路径
1、路径
* web.xml中<url-pattern>路径, 叫它Servlet路径
* 转发和包含路径
以"/"开头:相对当前项目路径
不以"/"开头:相对当前Serclet路径
* 重定向路径(客户端路径)
以"/"开头:相对当前主机