jsp的servlet容器跳转是出现乱码 挺经典的

今天写程序时,用一个Servlet跳转到JSP页面后该JSP页面出现乱码,但是直接在IE运行该JSP不出现乱码

出问题的代码如下:

  1. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  2.         // TODO Auto-generated method stub
  3.         
  4.         PrintWriter out = response.getWriter();
  5.         response.setContentType("type=text/html; charset=GBK");
  6.         String username = request.getParameter("username");
  7.         out = response.getWriter();
  8.         out.println("<html><head><title>处理</title></head><body>");
  9.         Check check = new Check();
  10.         check.setName(username);
  11.         System.out.println(check.getName());
  12.         
  13.         if(check.checkName()){
  14.             request.setAttribute("username", check.getName());
  15.             request.getRequestDispatcher("login_success.jsp").forward(request, response);
  16.         }else
  17.             request.getRequestDispatcher("faile.jsp").forward(request, response);
  18.         out.println("</body></html>");
  19.     }      

 问题如下:如果用该servlet运行跳转到JSP页面,就会出现乱码,如果把PrintWriter out去掉,就不会出现乱码。

具体原因:因为在设置编码之前就获得PrintWriter对象,所以必然出现乱码

解决办法:在获得PrintWriter对象之前就设置好编码,这样就不会出现问题

正确代码:

  1. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  2.         // TODO Auto-generated method stub
  3.         
  4.         request.setCharacterEncoding("GBK");
  5.         response.setContentType("GBK");
  6.         PrintWriter out = null;
  7.         response.setContentType("type=text/html; charset=GBK");
  8.         String username = request.getParameter("username");
  9.         username = new String(username.getBytes("iso-8859-1"),"GBK");
  10.         out = response.getWriter();
  11.         out.println("<html><head><title>处理</title></head><body>");
  12.         Check check = new Check();
  13.         check.setName(username);
  14.         System.out.println(check.getName());
  15.         
  16.         if(check.checkName()){
  17.             request.setAttribute("username", check.getName());
  18.             request.getRequestDispatcher("login_success.jsp").forward(request, response);
  19.         }else
  20.             request.getRequestDispatcher("faile.jsp").forward(request, response);
  21.         out.println("</body></html>");
  22.     }           

这样就解决问题了

你可能感兴趣的:(servlet)