[] A thorough understanding of Servlet doGet and doPost Chinese garbage problem

When we javaWeb project, and use doget dopost will always be a variety of reasons Chinese garbage problem, the landlord after a lot of information, why there will be such a problem, how to solve this problem and make a summary.

1. First throw doPost method request.getParameter ( "xxx"); garbled solution

In the beginning of the method body plus:

//设置request对象的解码方式
request.setCharacterEncoding("utf-8");

Encoding format string thus obtained is utf-8, the console Chinese distortion can be solved; (At this time the output page PrintWriter distortion still present)

2.doGet and doPost use PrintWriter out = response.getWriter (); Solution distortion output

In PrintWriter out = response.getWriter (); preceded by:

//设置response返回输出的编码方式
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();

With respect to these two added:

response.setHeader("Content-type", "text/html;charset=UTF-8");  
response.setCharacterEncoding("UTF-8");  
PrintWriter out = response.getWriter();

3. highlights: doGet method request.getParameter ( "xxx"); garbled solution

Why do we like to use doPost ? Because it is safe, it unlimited capacity, which is followed by body requset request over the data,

Means

request.setCharacterEncoding ( "utf-8"); it works! Encodes a code value problem solving, not Yoshiya?

The doGet method? Unsafe (URL will be shipped back parameter), small capacity (up to 1,2KB), the data do not follow requset request body , but on the end of the URL!

Means

request.setCharacterEncoding ( "utf-8"); no use for the doGet, we need additional transcoding, Gee, Haofan ~

Among the re-: tomcat different versions, different default encoding to resolve the url

Before tomcat8.0 version

Before tomcat8.0 version, the default encoding is ISO-8859-1

Solution 1: Manual string transcoding

So we can see many people doget Chinese garbled solve is this:

String username=new String(request.getParameter("username").getBytes("ISO-8859-1"), "UTF-8");

Because the default encoding is ISO-8859-1, with getBytes ( "ISO-8859-1") to get the original code byte array, and then converted to a String utf-8 encoded by the new.

But the drawback is that each parameter must be transcoded, you can change your brain to tremble ~

Solution 2: Modify the default encoded as UTF-8

Since the default encoding is ISO-8859-1, then modify the default encoding like

Find tomcat directory \\ conf \ server.xml

添加 URIEncoding="UTF-8"

After the addition, analytic encoding is UTF-8, doGet values ​​do not need to take a page from transcoded

However, this method is not recommended, because of the different circumstances of each machine, run on your machine, to others it is not run.

Solution 3: Filters transcoding

Online there are examples:

He wrote more full, dopost and can be configured both doget

Servlet filter to solve the Chinese garbled

After tomcat8.0 version

After tomcat8.0 version, a default encoding. 8-UTF , equivalent added URIEncoding = "UTF-8" (i.e. above the solution 2) before 8.0

At this point doget very easy to use, saving even more than dopost line request.setCharacterEncoding ( "utf-8");

Gratifying ~

dopost still the same, adding that things have to add!

4. Specific examples of

Examples tomcat 7 (no servlet.xml modify default encoding is ISO-8859-1, doget need to manually transcoding )

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


@WebServlet(
        urlPatterns = "/RequestParamsServlet"
)
public class RequestParamsServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置request对象的解码方式
        request.setCharacterEncoding("utf-8");
        //设置response返回输出的编码方式
        response.setContentType("text/html;charset=utf-8");
        String name = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("用户名:" + name);
        System.out.println("密 码:" + password);
        PrintWriter out = response.getWriter();
        out.println("用户名:" + name);
        out.println("密 码:" + password);
        // 获取参数名为“hobby”的值
        String[] hobbys = request.getParameterValues("hobby");
        System.out.print("爱好:");
        out.println("爱好:");
        for (int i = 0; i < hobbys.length; i++) {
            System.out.print(hobbys[i] + ",");
            out.println(hobbys[i] + ",");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       //设置response返回输出的编码方式
        response.setContentType("text/html;charset=utf-8");
        String name=new String(request.getParameter("username").getBytes("ISO-8859-1"), "UTF-8");
        String password=new String(request.getParameter("password").getBytes("ISO-8859-1"), "UTF-8");
        System.out.println("用户名:" + name);
        System.out.println("密 码:" + password);
        PrintWriter out = response.getWriter();
        out.println("用户名:" + name);
        out.println("密 码:" + password);
        // 获取参数名为“hobby”的值
        String[] hobbys = request.getParameterValues("hobby");
        System.out.print("爱好:");
        out.println("爱好:");
        for (int i = 0; i < hobbys.length; i++) {
            hobbys[i]=new String(hobbys[i].getBytes("ISO-8859-1"),"UTF-8");
            System.out.print(hobbys[i] + ",");
            out.println(hobbys[i] + ",");
        }

    }
}

Examples tomcat 9 (no servlet.xml modify default encoding is UTF-8, doget without transcoding )

package org.hc.maven.testnew;

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


@WebServlet(
        urlPatterns = "/RequestParamsServlet"
)
public class RequestParamsServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置request对象的解码方式
        request.setCharacterEncoding("utf-8");
        //设置response返回输出的编码方式
        response.setContentType("text/html;charset=utf-8");
        String name = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("用户名:" + name);
        System.out.println("密 码:" + password);
        PrintWriter out = response.getWriter();
        out.println("用户名:" + name);
        out.println("密 码:" + password);
        // 获取参数名为“hobby”的值
        String[] hobbys = request.getParameterValues("hobby");
        System.out.print("爱好:");
        out.println("爱好:");
        for (int i = 0; i < hobbys.length; i++) {
            System.out.print(hobbys[i] + ",");
            out.println(hobbys[i] + ",");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       //设置response返回输出的编码方式
        response.setContentType("text/html;charset=utf-8");
        String name = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("用户名:" + name);
        System.out.println("密 码:" + password);
        PrintWriter out = response.getWriter();
        out.println("用户名:" + name);
        out.println("密 码:" + password);
        // 获取参数名为“hobby”的值
        String[] hobbys = request.getParameterValues("hobby");
        System.out.print("爱好:");
        out.println("爱好:");
        for (int i = 0; i < hobbys.length; i++) {
            System.out.print(hobbys[i] + ",");
            out.println(hobbys[i] + ",");
        }

    }
}

Pro-test oh absolutely right, there is an error to see the students pay attention to servlet.xml tomcat is not added redundant configuration, or idea of ​​the character encoding configuration editor is wrong.

I believe seriously read here, on the issue of Chinese garbled already know

If you help, support what the point of praise ~

 

 

 

Published 14 original articles · won praise 14 · views 1116

Guess you like

Origin blog.csdn.net/qq_42495847/article/details/105237768