今天写程序时,用一个Servlet跳转到JSP页面后该JSP页面出现乱码,但是直接在IE运行该JSP不出现乱码
出问题的代码如下:
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- // TODO Auto-generated method stub
- PrintWriter out = response.getWriter();
- response.setContentType("type=text/html; charset=GBK");
- String username = request.getParameter("username");
- out = response.getWriter();
- out.println("<html><head><title>处理</title></head><body>");
- Check check = new Check();
- check.setName(username);
- System.out.println(check.getName());
- if(check.checkName()){
- request.setAttribute("username", check.getName());
- request.getRequestDispatcher("login_success.jsp").forward(request, response);
- }else
- request.getRequestDispatcher("faile.jsp").forward(request, response);
- out.println("</body></html>");
- }
问题如下:如果用该servlet运行跳转到JSP页面,就会出现乱码,如果把PrintWriter out去掉,就不会出现乱码。
具体原因:因为在设置编码之前就获得PrintWriter对象,所以必然出现乱码
解决办法:在获得PrintWriter对象之前就设置好编码,这样就不会出现问题
正确代码:
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- // TODO Auto-generated method stub
- request.setCharacterEncoding("GBK");
- response.setContentType("GBK");
- PrintWriter out = null;
- response.setContentType("type=text/html; charset=GBK");
- String username = request.getParameter("username");
- username = new String(username.getBytes("iso-8859-1"),"GBK");
- out = response.getWriter();
- out.println("<html><head><title>处理</title></head><body>");
- Check check = new Check();
- check.setName(username);
- System.out.println(check.getName());
- if(check.checkName()){
- request.setAttribute("username", check.getName());
- request.getRequestDispatcher("login_success.jsp").forward(request, response);
- }else
- request.getRequestDispatcher("faile.jsp").forward(request, response);
- out.println("</body></html>");
- }
这样就解决问题了