How do you obtain request parameters in a servlet?

In Servlet, you can retrieve request parameters using the following method:

  1. Retrieve the value of a single request parameter using the request.getParameter(String name) method, where “name” is the parameter’s name. This method returns a string, which is the value of the parameter.
  2. Retrieve the values of multiple request parameters with the method request.getParameterValues(String name). This method will return a string array containing the values of the parameters.
  3. Use the request.getParameterMap() method to fetch the values of all request parameters. This method returns a Map object, where the keys are the parameter names and the values are the parameter values.

Here is an example code for retrieving request parameters:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 获取单个请求参数的值
    String username = request.getParameter("username");
    String password = request.getParameter("password");

    // 获取多个相同名称的请求参数的值
    String[] hobbies = request.getParameterValues("hobby");

    // 获取所有请求参数的值
    Map<String, String[]> parameterMap = request.getParameterMap();

    // 处理请求参数的值
    // ...
}

It is important to note that the getParameter() method can only retrieve parameter values from POST and GET requests. For other request methods like PUT or DELETE, you can use the request.getInputStream() method to retrieve the data in the request body and then parse it yourself.

bannerAds