- 2、请求编码
- *客户端发送给服务器的请求参数是什么编码:
- 客户端首先要打开一个页面,然后在页面中提交表单或点击超链接,在请求这个页面时,服务器响应的编码是什么,那么客服端发送请求时就是什么
- *服务器端默认使用什么编码来解码参数:
- 服务器端默认使用ISO-8859-1来解码,所以这一定会出现乱码,因为iso不支持中文。
- *请求编码处理分为两种:GET和POST,GET请求参数不在请求体中,而POST请求参数在请求体中,所以它们的处理方式是不同的。
- *GET请求编码处理:
- 》String username = new String(request.getParmeter(“iso-8859-1”),“utf-8”);
- 》在servlet.xml中配置URIEncoding(“utf-8”);
- *POST请求编码处理
- 》String username = new String(request.getParameter(“iso-8859-1”),“utf-8”);
- 》在获取参数之前调用request.setCharacterEncoding(“utf-8”);
public class AServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/**
- 1、先获取来使用iso的错误字符串
- 2、回退,使用utf-8重编
/
String name = request.getParameter(“username”);
byte[] b = name.getBytes(“iso-8859-1”);
name = new String(b,“utf-8”);
System.out.println(name);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/* - 1、在获取参数之前,需要先调用request.setCharacterEncoding(“utf-8”);
- 2、使用getParameter()来获取参数
*/
request.setCharacterEncoding(“utf-8”);
String username = request.getParameter(“username”);
System.out.println(username);
}
}