关于处理JavaWeb中Servlet中返回jsp乱码问题

时间:2022-12-23 13:10:51

首先上效果图

关于处理JavaWeb中Servlet中返回jsp乱码问题

对于处理乱码主要分为三步第一步在Servlet获取输出流之前设置编码方式utf-8或者gbk

第二步在jsp中设置,第三步通过新建一个过滤器在web.xml里面配置。

request.setCharacterEncoding("utf-8");

response.setCharacterEncoding("utf-8");

response.setContentType("text/html;charset=utf-8");

PrintWriter out = response.getWriter();//获得对象的输出流
String name=request.getParameter("uname");
String pwd=request.getParameter("password");
UserDao dao=new UserDaoImpl();
UserInfo info=dao.getUserByUserPwd(name, pwd);
String str="";
if(info!=null){
     str="登录成功";
     Cookie username=new Cookie("uname",URLEncoder.encode(name, "utf-8"));
     username.setMaxAge(200);
     response.addCookie(username);
      Cookie upwd=new Cookie("password",pwd);
     upwd.setMaxAge(200);
     response.addCookie(upwd);
     HttpSession session=request.getSession();//获取Session对象
     session.setAttribute("loginUser", info);
     response.sendRedirect("servlet/success.jsp");
     //rd.forward(request, response);
   
 }else{
     str="登录失败";
     str=URLEncoder.encode(str,"utf-8");
   //  doGet(request, response);
     
     response.sendRedirect("servlet/login.jsp?error="+str);//重定向
  }

out.flush();
out.close();
}

然后jsp页面

     String error = new String(request.getParameter("error").getBytes("ISO8859-1"),"utf-8");
if (error != null) {
%>
<tr>
<td colspan="2"><%=error%></td>
</tr>
<%
}
%>

这样就ok了

自定义过滤器

request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
filter.doFilter(request, response);


最后别忘了在web.xml里面配置

<filter>
    <filter-name>CharsetFilter</filter-name>
    <filter-class>filter.CharsetFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>CharsetFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>