|
使用一个简单的html页面接受中文输入,再回显给相应页面,出现中文乱码。
需要注意,html页面中的编码属性,如果与响应方法中的request对象设定的编码不同,会出现乱码:
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
servlet中的方法如下:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print("你输入的用户名:");
out.print(request.getParameter("username"));
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print("你输入的用户名:");
//GET方法代码转换
String username=request.getParameter("username");
username =new String(username.getBytes("ISO8859-1"),"UTF-8");
out.print(username);
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
这样就不出现中文乱码 |
|
|