response.getWriter().print("中文")亂碼解決

解決方法是在response.getWriter()前加上response..setContentType("text/html; charset=UTF-8");html

下面是示例代碼,注意代碼中的紅色字體:session

protected void doGet(HttpServletRequest req, HttpServletResponse resp)jsp

throws ServletException, IOException {字體

req.setCharacterEncoding("utf-8");spa

User user=(User)req.getSession().getAttribute("user");htm

if(null==user){utf-8

req.getRequestDispatcher("session/userLogin.jsp").forward(req, resp);get

//避免惡意用戶直接在地址欄訪問localhost:8080/test/UpdateServletit

return;io

}

//!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("無權限");

}

}

相關文章
相關標籤/搜索