servelet编码处理

public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8"); //请求编码POST
        resp.setContentType("text/html;charset=utf-8"); //响应编码

        UserService userService = new UserService();
    }
}

Get是URL解码方式。默认解码格式是Tomcat8编码格式。所以URL解码是UTF-8,
覆盖掉了request容器解码格式
Post是实体内容解码方式。默认解码格式是request编码格式。与Tomcat8编码格式无关

tomcat服务器中Response容器默认以ISO8859-1的编码解析数据,因此如果需要在参数中解析中文,需要设置

request.setCharacterEncoding(“utf-8”);

post得到前台数据:(request容器默认是gbk格式)
request.setCharacterEncoding(“utf-8”);
System.out.println(request.getParameter(“name”));

GET得到前台数据:(不需要设置编码格式,默认是按照tomcat服务器的编码格式)
System.out.println(request.getParameter(“name”));

GET POST给前台传数据
response.setCharacterEncoding(“utf-8”);
response.getWriter().write(“我爱你”);

猜你喜欢

转载自blog.csdn.net/yemenlinweihan/article/details/107593929