JAVA --- How does Servlet (response and request) solve the Chinese garbled problem?

For Request: Type
before writing the method:request.setCharacterEncoding("utf-8")

@WebServlet("/RequestDemo9")
public class RequestDemo9 extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        request.setCharacterEncoding("utf-8");
        Object msg = request.getAttribute("msg");
        System.out.println(msg);
        System.out.println("demo9在访问...");
    }

For Response:
Step1. You need to set the encoding
Step2. You need to inform the browser that the encoding format of the message sent by the server The
following three methods are essentially the same, and can solve the response garbled problem. The three of them are language to provide a more concise progression.
Method 1:

 response.setCharacterEncoding("utf-8");
 response.setHeader("content-type","text/html;charset=utf-8");

Method 2:

 response.setHeader("content-type","text/html;charset=utf-8");

Method Three:

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

Since the third method is the simplest, it is also a frequently used method.

Guess you like

Origin blog.csdn.net/Forest_2Cat/article/details/107769690