Chinese garbled problem of getting page parameters

Chinese garbled problem of getting page parameters

When the page parameter is obtained through the getParameter("name") method, when the page parameter is input in Chinese, the obtained Chinese parameter will have the problem of garbled characters.
E.g:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="test01" method="post">
    账号:<input type="text" placeholder="请输入姓名" name="username">
    <br>
    密码:<input type="text" placeholder="请输入密码" name="password">
    <input type="submit" value="提交">
</form>
</body>
</html>

operation result:
Insert picture description here

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;

@WebServlet("/test01")
public class test01_Servlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        String username = request.getParameter("username");   //获取username的值
        System.out.println(username);    //打印
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doPost(request, response);
    }
}

Insert picture description here
get method: garbled characters will not appear in the submission, because the problem has been solved internally in Tomcat.
Post method: garbled characters will appear

Solution:
Set the character encoding format of the stream, because when using the post request, the request body is packaged into a stream, and it is necessary
to set the same character encoding format as the previous port page.

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;

@WebServlet("/test01")
public class test01_Servlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        request.setCharacterEncoding("utf-8");   //设置编码格式
        String username = request.getParameter("username");
        System.out.println(username);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doPost(request, response);
    }
}

operation result:
Insert picture description here

Guess you like

Origin blog.csdn.net/tan1024/article/details/111560572
Recommended