解决方法是在response.getWriter()前加上response..setContentType("text/html; charset=UTF-8");
下面是示例代码,注意代码中的红色字体:
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
User user=(User)req.getSession().getAttribute("user");
if(null==user){
req.getRequestDispatcher("session/userLogin.jsp").forward(req, resp);
//避免恶意用户直接在地址栏访问localhost:8080/test/UpdateServlet
return;
}
//!resp.setCharacterEncoding("utf-8");单纯的这么设置一样有乱码
resp.setContentType("text/html; charset=UTF-8");
PrintWriter out=resp.getWriter();
if("admin".equals(user.getAuthority())){
out.print("成功");
}else{
out.print("无权限");
}
}
时间: 2024-10-23 18:08:07