Detailed explanation of obtaining request parameters in SpringMVC

Article Directory

        1. Obtained through ServletAPI
    1. Obtain the request parameters through the formal parameters of the controller method
  • 3、[@RequestParam ](/RequestParam )
  • 4、[@RequestHeader ](/RequestHeader )
  • 5、[@CookieValue ](/CookieValue )
    1. Obtain request parameters through POJO
    1. Solve the garbled problem of obtaining request parameters
  • Summarize

In Spring MVC, there are many ways to obtain request parameters. Let's start with a side dish and use the @RequestParam annotation to obtain request parameters.

The @RequestParam annotation can be used on method parameters to specify the name of the request parameter. For example, if your request parameter is named “username”, you can use @RequestParam(“username”) on the method parameter to get the value of the parameter.

@Controller
public class MyController {

    @RequestMapping("/myEndpoint")
    public String myEndpoint(@RequestParam("username") String username) {
        // available hereusernameParameters are processed
        return "result";
    }
} 

In the above example, when the request reaches “/myEndpoint”, Spring MVC will automatically assign the value of the request parameter named “username” to the method parameter username. You can handle this parameter according to your needs.

Let’s explain in detail how SpringMVC obtains request parameters.

1. Obtain through ServletAPI

Use HttpServletRequest as a formal parameter of the controller method. At this time, the parameter of type HttpServletRequest represents an object that encapsulates the request message of the current request.

@RequestMapping("/testParam")
public String testParam(HttpServletRequest request){
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    System.out.println("username:"+username+",password:"+password);
    return "success";
} 

2. Obtain request parameters through the formal parameters of the controller method

In the formal parameter position of the controller method, set the formal parameter with the same name as the request parameter. When the browser sends a request and matches the request mapping, the request parameter will be assigned to the corresponding formal parameter in DispatcherServlet.

<a th:href="@{/testParam(username='admin',password=123456)}">
  Test to get request parameters-->/testParam</a><br> 
@RequestMapping("/testParam")
public String testParam(String username, String password){
    System.out.println("username:"+username+",password:"+password);
    return "success";
} 

Note:
If there are multiple request parameters with the same name in the request parameters transmitted by the request, you can set a string array or string type parameter in the formal parameter of the controller method to receive this request parameter.
If a formal parameter of string array type is used, the array of this parameter contains each data
If a string type parameter is used, the value of this parameter is the result of concatenating each data with a comma.

3、@RequestParam

@RequestParam creates a mapping relationship between request parameters and formal parameters of the controller method.
The @RequestParam annotation has three attributes:
value: Specifies the parameter name of the request parameter assigned to the formal parameter.
required: Set whether this request parameter must be transmitted, the default value is true

If set to true, the current request must transmit the request parameter specified by value. If the request parameter is not transmitted and the defaultValue attribute is not set, the page will report error 400: Required String parameter 'xxx' is not present; if set to false , then the current request does not have to transmit the request parameter specified by value. If it is not transmitted, the value of the formal parameter identified by the annotation is null.

defaultValue: Regardless of whether the required attribute value is true or false, when the request parameter specified by value is not transmitted or the transmitted value is “”, the default value is used to assign the formal parameter.

4、@RequestHeader

@RequestHeader creates a mapping relationship between the request header information and the formal parameters of the controller method.
The @RequestHeader annotation has three attributes: value, required, and defaultValue. The usage is the same as @RequestParam.

5、@CookieValue

@CookieValue creates a mapping relationship between cookie data and formal parameters of the controller method.
The @CookieValue annotation has three attributes: value, required, and defaultValue. The usage is the same as @RequestParam.

6. Obtain request parameters through POJO

You can set a formal parameter of the entity class type in the formal parameter position of the controller method. At this time, if the parameter name of the request parameter transmitted by the browser is consistent with the attribute name in the entity class, then the request parameter will be assigned a value for this attribute.

<form th:action="@{/testpojo}" method="post">
    username:<input type="text" name="username"><br>
    password:<input type="password" name="password"><br>
    gender:<input type="radio" name="sex" value="male">male<input type="radio" name="sex" value="female">female<br>
    age:<input type="text" name="age"><br>
    Mail:<input type="text" name="email"><br>
    <input type="submit">
</form> 
@RequestMapping("/testpojo")
public String testPOJO(User user){
    System.out.println(user);
    return "success";
}
//Final Results-->User{id=null, username='Zhang San', password='123', age=23, sex='male', email='123@qq.com'} 

7. Solve the garbled problem of obtaining request parameters

To solve the garbled problem of obtaining request parameters, you can use the encoding filter CharacterEncodingFilter provided by SpringMVC, but it must be registered in web.xml

<!--ConfigurationspringMVCencoding filter-->
<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceResponseEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping> 

Note:

The filter that handles encoding in SpringMVC must be configured before other filters, otherwise it will be invalid.

Summarize

The main content of this article:

  1. Obtain through ServletAPI: You can use the HttpServletRequest object to obtain request parameters. The value of the specified parameter can be obtained by calling the request.getParameter(“parameter name”) method.

  2. Obtain the request parameters through the formal parameters of the controller method: You can directly declare the parameter name on the parameters of the controller method, and Spring MVC will automatically assign the value of the request parameter to the corresponding parameter.

  3. @RequestParam annotation: You can use the @RequestParam annotation on the parameters of the controller method to obtain the request parameters. By specifying @RequestParam(“parameter name”), Spring MVC will assign the value of the request parameter to the corresponding parameter.

  4. @RequestHeader annotation: You can use the @RequestHeader annotation on the parameters of the controller method to obtain the request header information. By specifying @RequestHeader(“header field name”), Spring MVC will assign the value of the request header to the corresponding parameter.

  5. @CookieValue annotation: You can use the @CookieValue annotation on the parameters of the controller method to obtain the value of the cookie. By specifying @CookieValue(“Cookie name”), Spring MVC will assign the cookie value to the corresponding parameter.

  6. Obtain request parameters through POJO: You can create a POJO class and match the name of the request parameter to the attribute name of the POJO class. Spring MVC will automatically assign the value of the request parameter to the attribute of the POJO class.

  7. Solve the garbled problem of obtaining request parameters: If the request parameters are garbled, you can configure the character encoding filter in the Spring MVC configuration file and set the encoding of the request parameters to the correct encoding method to solve the garbled problem.

Insert image description here