SpringMVC–@RequestMapping annotation

@RequestMapping annotation

  • The function of @RequestMapping annotation
  • The location of the @RequestMapping annotation
  • @RequestMapping annotated properties
    • 1. value attribute
    • 2. method attribute
    • 3. params attribute (understand)
  • Replenish
    • @RequestParam
    • @RequestHeader
    • @RequestBody
      • @RequestBody gets request parameters in json format
    • @ResponseBody
    • @RestController annotation

Function of @RequestMapping annotation

The function of the @RequestMapping annotation is to associate the request with the controller method that handles the request.
Get up and establish a mapping relationship.
When SpringMVC receives the specified request, it will find the corresponding controller method in the mapping relationship to handle the request.

The location of the @RequestMapping annotation

@RequestMapping identifies a class: sets the initial information of the request path of the mapping request
@RequestMapping identifies a method: sets the specific information of the mapping request request path

Attributes of the @RequestMapping annotation

1. value attribute

The value and attributes of the @RequestMapping annotation match the request mapping through the requested request address.
The value attribute of the @RequestMapping annotation is an array of string type, indicating that the request mapping can match requests corresponding to multiple request addresses. The value attribute of the @RequestMapping annotation must be set, at least through the request address to match the request mapping.

<a th:href="@{/testRequestMapping}">Test the value attribute of @RequestMapping--
>/testRequestMapping</a><br>
<a th:href="@{/test}">Test the value attribute of @RequestMapping-->/test</a><br>
@RequestMapping(
value = {<!-- -->"/testRequestMapping", "/test"}
)
public String testRequestMapping(){<!-- -->
return "success";
}

2. method attribute

The method attribute of the @RequestMapping annotation matches the request mapping through the request method (get or post)
The method attribute of the @RequestMapping annotation is an array of RequestMethod type, indicating that the request mapping can match
Multiple request methods
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 will report an error.
405:Request method POST’ not supported

<a th:href="@{/test}">Test the value attribute of @RequestMapping-->/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. For controller methods that handle specified request methods, SpringMVC provides the derived annotation @RequestMapping
Mapping that handles get requests–>@GetMapping
Mapping for processing post requests–>@PostMapping
Mapping for processing put requests–>@PutMapping
Mapping to handle delete requests–>@DeleteMapping
2. Commonly used request methods include get, post, put, delete
However, currently browsers only support get and post. If the form is submitted, the characters of other request methods are set for the method.
string (put or delete), it will be processed according to the default request method get
To send put and delete requests, you need to pass the filter HiddenHttpMethodFilter provided by spring, in
The RESTful part will be discussed.

3. params attribute (understanding)

The params attribute of the @RequestMapping annotation matches the request mapping through the request parameters of the request
The params attribute of the @RequestMapping annotation is an array of string type, and request parameters can be set through four expressions
Matching relationship with request mapping
“param”: The request matched by the request mapping must carry the param request parameter
“!param”: The request matched by the request mapping must not carry param request parameters
“param=value”: The request matched by the request mapping must carry the param request parameter and param=value
“param!=value”: The request matched by the request mapping must carry the param request parameter but param!=value

<a th:href="@{/test(username='admin',password=123456)">Testing @RequestMapping
params attribute-->/test</a><br>
@RequestMapping(
value = {<!-- -->"/testRequestMapping", "/test"}
,method = {<!-- -->RequestMethod.GET, RequestMethod.POST}
,params = {<!-- -->"username","password!=123456"}
)
public String testRequestMapping(){<!-- -->
return "success";
}

Supplement

@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 is not set
defaultValue attribute, the page reports 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 has no transmitted or transmitted value
When it is “”, the default value is used to assign the formal parameter.

@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.

@RequestBody

@RequestBody can obtain the request body information. Use the @RequestBody annotation to identify the formal parameters of the controller method. Please refer to the current request
Seeking the body will assign a value to the formal parameter identified by the current annotation.

<!--The post request method must be used at this time, because the get request does not have a request body-->
<form th:action="@{/test/RequestBody}" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit">
</form>
@RequestMapping("/test/RequestBody")
public String testRequestBody(@RequestBody String requestBody){<!-- -->
System.out.println("requestBody:" + requestBody);
return "success";
}

Output result:
requestBody:username=admin & amp;password=123456

@RequestBody gets request parameters in json format

After using axios to send an ajax request, the request parameters sent by the browser to the server have two formats:
1. name=value & name=value…, the request parameters at this time can be obtained through request.getParameter(), corresponding to
In SpringMVC, such request parameters can be obtained directly through the formal parameters of the controller method.
2. {key:value,key:value,…}, which cannot be obtained through request.getParameter() at this time. We used the operation before
The related jar package gson or jackson of json handles such request parameters and can convert them into specified entity class objects or map sets
combine. In SpringMVC, you can directly use the @RequestBody annotation to identify the formal parameters of the controller method to add such request parameters.
Convert to java object

Conditions for using @RequestBody to obtain request parameters in json format:
①. Import Jackson’s dependencies

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>

② Set up the annotation driver for mvc in the SpringMVC configuration file.

<!--Enable mvc annotation driver-->
<mvc:annotation-driven />

3. In the formal parameter position of the controller method, set the parameters of the java type (entity class or map) to be converted from the json format request parameters.
number, and use the @RequestBody annotation to identify

<input type="button" value="Test @RequestBody to get request parameters in json format"
       @click="testRequestBody()"><br>
<script type="text/javascript" th:src="@{/js/vue.js}"></script>
<script type="text/javascript" th:src="@{/js/axios.min.js}"></script>
<script type="text/javascript">
    var vue = new Vue({<!-- -->
        el:"#app",
        methods:{<!-- -->
            testRequestBody(){<!-- -->
                axios.post(
                    "/SpringMVC/test/RequestBody/json",
                    {<!-- -->username:"admin",password:"123456"}
                ).then(response=>{<!-- -->
                    console.log(response.data);
                });
            }
        }
    });
</script>

@ResponseBody

@ResponseBody is used to identify a controller method, and the return value of the method can be directly responded to the browser as the response body of the response message.

@RequestMapping("/testResponseBody")
public String testResponseBody(){<!-- -->
//This will jump to the page corresponding to the logical view success.
        return"success";
        }
@RequestMapping("/testResponseBody")
@ResponseBody
public String testResponseBody(){<!-- -->
//Respond to browser data success at this time
        return"success";
        }

@ResponseBody responds to browser json data
After the server processes the ajax request, in most cases it needs to respond to the browser with a java object. At this time, the java object must be converted to
Only json strings can be responded to the browser. Previously, we used the jar package gson or jackson to operate json data to convert the java object into
json string. In SpringMVC, we can directly use the @ResponseBody annotation to implement this function
Conditions for @ResponseBody to respond to browser json data
1. Import Jackson’s dependencies

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>

2. Set up the annotation driver for mvc in the SpringMVC configuration file.

<!--Enable mvc annotation driver-->
<mvc:annotation-driven />

3. Use the @ResponseBody annotation to identify the controller method. In the method, convert the need to a json string and respond to the browser
The java object is used as the return value of the controller method. At this time, SpringMVC can directly convert this object into a json string and respond to the browser.

<input type="button" value="Test @ResponseBody to respond to browser json format data"
       @click="testResponseBody()"><br>
<script type="text/javascript" th:src="@{/js/vue.js}"></script>
<script type="text/javascript" th:src="@{/js/axios.min.js}"></script>
<script type="text/javascript">
    var vue = new Vue({<!-- -->
        el: "#app",
        methods: {<!-- -->
            testResponseBody() {<!-- -->
                axios.post("/SpringMVC/test/ResponseBody/json").then(response => {<!-- -->
                    console.log(response.data);
                });
            }
        }
    });
</script>
//Response to browser list collection
@RequestMapping("/test/ResponseBody/json")
@ResponseBody
public List<User> testResponseBody(){<!-- -->
        User user1 = new User(1001,"admin1","123456",23,"Male");
        User user2 = new User(1002,"admin2","123456",23,"Male");
        User user3 = new User(1003,"admin3","123456",23,"Male");
        List<User> list = Arrays.asList(user1, user2, user3);
        return list;
        }

@RestController annotation

The @RestController annotation is a composite annotation provided by springMVC. It is marked on the controller class, which is equivalent to adding it to the class.
@Controller annotation, and added @ResponseBody annotation for each method