MENU

JavaWeb使用response的中文乱码问题

March 3, 2020 • Read: 73 • Note,JavaWeb

原生JavaWeb使用response的中文乱码问题
继承HttpServlet后重写方法时加入两行代码设置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>");
    }

本站所有未注明转载的文章均为原创,并采用CC BY-NV-SA 4.0 授权协议,转载请注明来源。

Last Modified: March 24, 2020
Archives QR Code
QR Code for this page
Tipping QR Code