心湖维基

JavaWeb使用response的中文乱码问题

原生JavaWeb使用response的中文乱码问题

继承HttpServlet后重写方法时(如doGet)加入两行代码设置utf-8编码

resp.setContentType("application/json;charset=utf-8");
resp.setCharacterEncoding("utf-8");
//需要加上方法的最上面,也就是在方法内容的首行.

完整示例:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<HTML>");
        out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>");
        out.println("<BODY>");
        out.println("我终于可以显示中文了");
        out.println("</BODY></HTML>");
    }
Copyright © 2020 乐心湖 Hosted By 云开发