How can a servlet receive data sent via a POST request?

In Servlet, you can use the methods of the HttpServletRequest object to receive POST request data.

  1. Obtaining the HttpServletRequest object:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 获取HttpServletRequest对象
    // ...
}
  1. Obtain POST request parameters:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 获取POST请求参数
    String param1 = request.getParameter("param1"); // 根据参数名获取单个参数的值
    String[] param2 = request.getParameterValues("param2"); // 根据参数名获取多个参数的值

    // ...
}

The method `getParameter()` is used to retrieve the value of a single parameter in the code above, while `getParameterValues()` is used to retrieve the values of multiple parameters. The parameters of these methods are the names of the request parameters.

  1. Retrieve the data from the POST request’s body.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 获取POST请求的Body中的数据
    String requestBody = request.getReader().lines()
            .reduce("", (accumulator, actual) -> accumulator + actual); // 将请求Body中的数据拼接成字符串

    // ...
}

The code above utilizes the getReader() method to obtain a BufferedReader object for the request, then uses the lines() method to read the data line by line, and the reduce() method to concatenate each line into a single string.

It is important to note that the above code is only applicable for text data in the request body. For binary data in the request body, such as file uploads, other methods need to be used.

bannerAds