SpringMVC Notes: @RequestMapping Notes

Posted by maGGot_H on Tue, 25 Jan 2022 21:19:11 +0100

Catalog

1. @RequestMapping annotation

1. @RequestMapping annotation function

2. @RequestMapping annotation location

3. @RequestMapping annotation value property

4. @RequestMapping annotation method property

5. @RequestMapping annotation params property (understand)

6. @RequestMapping annotation headers property (understand)

7. SpringMVC supports ant style paths

8. SpringMVC supports placeholders in paths (emphasis)

2. SpringMVC Get Request Parameters

1. Obtained through the Servlet API

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

3,@RequestParam

4,@RequestHeader

5,@CookieValue

6. Obtain request parameters through POJO

7. Solve the problem of scrambling to get request parameters

1. @RequestMapping annotation

1. @RequestMapping annotation function

As you can see from the annotation name, the @RequestMapping annotation is used to associate the request with the controller method that handles the request and establish a mapping relationship.

When SpringMVC receives the specified request, it will find the corresponding controller method in the mapping relationship to process the request.

2. @RequestMapping annotation location

  • @RequestMapping identifies a class that sets the initial information for the request path of the mapping request
  • @RequestMapping identifies a method for setting specific information about the path of a map request request
@Controller
@RequestMapping("/test")
public class RequestMappingController {

    //The request path for the request mapped by the request mapping is: /test/testRequestMapping
    @RequestMapping("/testRequestMapping")
    public String testRequestMapping(){
        return "success";
    }

}

3. @RequestMapping annotation value property

The value property of the @RequestMapping annotation matches the request mapping by the request address of the request

The value property of the @RequestMapping annotation is an array of string types indicating that the request mapping can match requests corresponding to multiple request addresses

The value property of the @RequestMapping annotation must be set, at least by request address matching request mapping

<a th:href="@{/testRequestMapping}">test@RequestMapping Of value attribute-->/testRequestMapping</a><br>
<a th:href="@{/test}">test@RequestMapping Of value attribute-->/test</a><br>

@RequestMapping(
        value = {"/testRequestMapping", "/test"}
)
public String testRequestMapping(){
    return "success";
}

4. @RequestMapping annotation method property

The method property of the @RequestMapping annotation matches the request mapping by the way the request is requested (get or post)

The method property of the @RequestMapping annotation is an array of RequestMethod types, indicating that the request mapping can match requests of multiple request modes

If the request address of the current request satisfies the value attribute of the request mapping, but the request method does not satisfy the method attribute, the browser error 405: Request method'POST'not supported

<a th:href="@{/test}">test@RequestMapping Of value attribute-->/test</a><br>

<form th:action="@{/test}" method="post">
    <input type="submit">
</form>

@RequestMapping(
        value = {"/testRequestMapping", "/test"},
        method = {RequestMethod.GET, RequestMethod.POST}
)
public String testRequestMapping(){
    return "success";
}Note:

1. Derived annotations for @RequestMapping are provided in SpringMVC for controller methods that handle specified requests

  • Mapping for processing get requests -->@GetMapping
  • Mapping for processing post requests -->@PostMapping
  • Mapping for processing put requests -->@PutMapping
  • Mapping for handling delete requests -->@DeleteMapping

2. Common requests are get, post, put, delete

  • However, browsers currently only support get and post. When a form form submission is made, a string (put or delete) with other request modes is set for the method, the default request mode for get processing is followed.
  • To send put and delete requests, you need to use the filter HiddenHttpMethodFilter provided by spring, which is described in the RESTful section

5. @RequestMapping annotation params property (understand)

The @RequestMapping annotation's params property matches the request mapping by the request parameter

The params property of the @RequestMapping annotation is an array of string types that allow you to set the matching relationship between request parameters and request mappings in four expressions

  • "Param": Requires that requests matching the request mapping must carry param request parameters
  • '!Param': Request mapping matches a request that must not carry param request parameters
  • "Param=value": Requires that requests matching the request mapping must carry a param request parameter and param=value
  • "param!=value": Requests that the request mapping matches must carry a param request parameter but param!= Value
<a th:href="@{/test(username='admin',password=123456)">test@RequestMapping Of params attribute-->/test</a><br>

@RequestMapping(
        value = {"/testRequestMapping", "/test"}
        ,method = {RequestMethod.GET, RequestMethod.POST}
        ,params = {"username","password!=123456"}
)
public String testRequestMapping(){
    return "success";
}
Note:
  • If the current request satisfies the value and method attributes of the @RequestMapping annotation but does not satisfy the params attribute, the page returns an error of 400:Parameter conditions "username, password!=123456" not met for actual request parameters: username={admin}, password={123456}

6. @RequestMapping annotation headers property (understand)

The headers property of the @RequestMapping annotation matches the request mapping with the request header information of the request

The headers property of the @RequestMapping annotation is an array of string types that allows you to set the matching relationship between the request header information and the request map in four expressions

  • "Header": Requires that requests matching the request map must carry header request header information
  • '!Header': Request mapping matches a request that must not carry header request header information
  • "Header=value": Require that requests matching the request map must carry header request header information and header=value
  • "header!=value": Requests that the request mapping match must carry header request header information and header!= Value

Note:

  • If the current request satisfies the value and method attributes of the @RequestMapping annotation but does not satisfy the headers attribute, the page displays a 404 error where the resource was not found

7. SpringMVC supports ant style paths

  • ?: Represents any single character
  • *: Represents any zero or more characters
  • **: Indicates any one or more levels of directory

Note: You can only use //xxx when using

8. SpringMVC supports placeholders in paths (emphasis)

Original way: /deleteUser?id=1

rest method: /deleteUser/1

Placeholders in SpringMVC paths are commonly used in the RESTful style. When certain data is routed to the server in the request path, the data transferred can be represented by the placeholder {xx} in the value attribute of the corresponding @RequestMapping annotation, and the data represented by the placeholder can be assigned to the parameter of the controller method through the @PathVariable annotation.

<a th:href="@{/testRest/1/admin}">Placeholder in test path-->/testRest</a><br>

@RequestMapping("/testRest/{id}/{username}")
public String testRest(@PathVariable("id") String id, @PathVariable("username") String username){
    System.out.println("id:"+id+",username:"+username);
    return "success";
}
//The final output is -->id:1, username:admin

2. SpringMVC Get Request Parameters

1. Obtained through the Servlet API

HttpServletRequest is used as a parameter to the controller method, where a parameter of type HttpServletRequest represents the object encapsulating 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 the request parameters through the parameters of the controller method

In the parameter location of the controller method, set the parameter with the same name as the request parameter, and when the browser sends the request and matches the request mapping, the request parameter is assigned to the corresponding parameter in the Dispatcher Servlet

<a th:href="@{/testParam(username='admin',password=123456)}">Test 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 the request is transmitted with more than one request parameter with the same name, then a string array or a string type parameter can be set in the parameter of the controller method to receive the request parameter.

If a parameter of type string array 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 using a comma stitch in the middle of each data

3,@RequestParam

@RequestParam creates a mapping relationship between the request parameters and the parameters of the controller method

The @RequestParam annotation has three properties:

value: The parameter name of the request parameter specified as a parameter assignment

required: Sets whether this request parameter must be transferred, defaulting to true

If set to true, the current request must transfer the request parameter specified by value. If the request parameter is not transferred and the defaultValue property is not set, the page error is 400:Required String parameter'xxx'is not present; If set to false, the current request does not have to transfer the request parameters specified by value. If not, the value of the parameter identified by the comment is null

Default Value: Whether the required property value is true or false, when the request parameter specified by value is not transmitted or the transmitted value is'', the parameter assignment is made using the default value

4,@RequestHeader

@RequestHeader creates a mapping relationship between the request header information and the parameters of the controller method

The @RequestHeader annotation has three properties: value, required, defaultValue, and is used in the same way as @RequestParam

5,@CookieValue

@CookieValue creates a mapping relationship between cookie data and the parameters of the controller method

The @CookieValue annotation has three properties: value, required, defaultValue, and is used in the same way as @RequestParam

6. Obtain request parameters through POJO

An entity class type parameter can be set at the parameter location of the controller method, and if the parameter name of the request parameter transmitted by the browser is the same as the property name in the entity class, the request parameter will be assigned a value for this property

<form th:action="@{/testpojo}" method="post">
    User name:<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>
    Mailbox:<input type="text" name="email"><br>
    <input type="submit">
</form>

@RequestMapping("/testpojo")
public String testPOJO(User user){
    System.out.println(user);
    return "success";
}
//Final result -->User{id=null, username='Zhang San', password='123', age=23, sex='man', email='123@qq.com '}

7. Solve the problem of scrambling to get request parameters

To solve the scrambling problem of getting request parameters, you can use the encoding filter CharacterEncoding Filter provided by SpringMVC, but it must be on the web. Register in XML

<!--To configure springMVC Coding filters for-->
<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:

Filters that process codes in SpringMVC must be configured before other filters, otherwise they are invalid

Topics: Java Spring MVC