Servlet页面解析中文乱码问题

提交表单时,中文可能会产生乱码


在Servlet中,在使用request和response之前设置一下request和response的编码格式为utf-8。
如下:

request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");

如果使用response.getWriter()输出html页面,应该设置浏览器显示的编码为utf-8。如下:

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

注意,编码的设置要写在getWriter前面

例程

package com.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class SampleServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //resp.getWriter向浏览器树出的数据流
        PrintWriter writer = resp.getWriter();
        writer.println("<a href='http://www.baidu.com'>Baidu</a>");
        String name = req.getParameter("name");
        writer.println("<h1>name="+name+"</h1>");


    }
}

你以为的极限,也许只是别人的起点
原文地址:https://www.cnblogs.com/LengDing/p/14469065.html