Learn SpringMVC -- GET Request Parameters and springmvc get Parameters
@ RequestParam, you must have seen it; @ PathVariable, you certainly know it; @ QueryParam, why don't you know it ?! You are also familiar with him (@ CookieValue )! She (@ ModelAndView )! It (@ ModelAttribute )! That's right. Just comment this piece, spring mvc opens a colorful world for you. Come and come, don't join (mi) Fen (hu), sit down, let's have a good chat with these annotation brothers ~~~ (Have you heard of wait? Okay, come on. You can sit in the front row. That's you !)
I. How does spring mvc match the Request Path? "which is the most popular Request Path? The RequestMapping name is far away"
@ RequestMapping is used to map requests, such as get requests, post requests, or REST and non-REST requests. This annotation can be used on a class or method. If it is used on a class, it indicates the parent path of all methods in the class.
Example (the test classes used here, such as SpringMVCTest and some pages, are described in the first article learning SpringMVC-starting from HelloWorld ):
Add the test method to SpringMVCTest. java:
@ RequestMapping ("/testRequestMapping ")
Public String testRequestMapping (){
System. out. println ("testRequestMapping ");
Return SUCCESS;
}
Note that the annotation @ RequestMapping ("/testRequestMapping") is added at the method level, indicating that the method can be located through the relative path of "/testRequestMapping, at the same time, we also put a class-level RequestMapping annotation in the SpringMVCTest class:
@ RequestMapping ("/springmvc ")
@ Controller
Public class SpringMVCTest {
Note that a @ Controller annotation is added here. This annotation is used in SpringMVC to process requests distributed by DispatcherServlet, it encapsulates the data requested by the user into a Model after being processed by the business processing layer, and then returns the Model to the corresponding View for display. Now we have a path like springmvc/testRequestMapping, so we can locate the testRequestMapping method and then execute the method body in the method.
Additionally, RequestMapping can implement Fuzzy Matching paths, for example:
? : Match a character
*: Match any character
**: Match multiple layers of paths
/Springmvc/**/lastTest can match paths like/springmvc/firstTest/secondTest/lastTest.
Ii. How does spring mvc obtain the request parameters-"The Eight Immortals go through the sea and show their advantages and disadvantages"
1. @ PathVariable
This annotation is used to map placeholders bound to the request URL. @ PathVariable can be used to bind the placeholder parameter in the URL to the input parameter of the controller processing method. do you understand this? Example:
@ RequestMapping ("/testPathVariable/{id }")
Public String testPathVariable (@ PathVariable (value = "id") Integer id ){
System. out. println ("testPathVariable:" + id );
Return SUCCESS;
}
In index. jsp, we add a connection to trigger a request:
<a href="springmvc/testPathVariable/1">testPathVariable</a><br/><br/>
We can see that there is a hyperlink here. After clicking it, it will go to the controller processing method corresponding to springmvc/testPathVariable/1, now we want to get "1" in this request parameter, So we add "/testPathVariable/id" to the testPathVariable method, about id ", specifically, the {id} corresponds to the parameter of this method. @ PathVariable (value = "id") is used to declare the request parameter to be received, and use Integer id to bind and receive data. In this way, we can get the parameter "1" requested by the front-end page ".
2. @ RequestParam
This annotation is also used to obtain request parameters. So what is the difference between this annotation and @ PathVariable? Let's look at the example:
Add a method to SpringMVCTest
@ RequestMapping (value = "/testRequestParam ")
Public String testRequestParam (@ RequestParam (value = "username") String username, @ RequestParam (value = "age", required = false, defaultValue = "0") int age ){
System. out. println ("testRequestParam" + "username:" + username + "age:" + age );
Return SUCCESS;
}
Add a hyperlink tag in index. jsp
<a href="springmvc/testRequestParam?username=jackie&age=12">testRequestParam</a><br/><br/>
Click the hyperlink on the page to match the RequestMapping path on the testRequestParam method in the controller. Note that in this method, we declare two variables through the annotation @ RequestParam to get the parameter value of the query in the request. One is the value after username, the other is the value after age.
Here, you probably understand the differences between @ PathVariable and @ RequestParam. For requests like springmvc/testPathVariable/1, we use @ PathVariable to bind the request parameters. For parameters similar to "springmvc/testRequestParam? Username = jackie & age = 12 "is a key-value pair. We use @ RequestParam to obtain the specific request value after username or age.
Similar to RequestParam, QueryParam is also used. Because it is not an annotation in the spring mvc framework, it is not described here.
Spring mvc provides a specific solution for different request types and methods, next, let's take a look at the popular REST-style requests-use the REST-style to add, delete, modify, and query requests.
In the SpringMVCTest class, the interfaces for querying (get) add (post) delete (delete) and modify (put) are implemented from the bottom up.
@ RequestMapping (value = "/testRest/{id}", method = RequestMethod. PUT)
Public String testRestPut (@ PathVariable (value = "id") Integer id ){
System. out. println ("test put:" + id );
Return SUCCESS;
}
@ RequestMapping (value = "/testRest/{id}", method = RequestMethod. DELETE)
Public String testRestDelete (@ PathVariable (value = "id") Integer id ){
System. out. println ("test delete:" + id );
Return SUCCESS;
}
@ RequestMapping (value = "/testRest", method = RequestMethod. POST)
Public String testRest (){
System. out. println ("test post ");
Return SUCCESS;
}
@ RequestMapping (value = "/testRest/{id}", method = RequestMethod. GET)
Public String testRest (@ PathVariable (value = "id") Integer id ){
System. out. println ("test get:" + id );
Return SUCCESS;
}
How can we implement the front-end interface?
<Form action = "springmvc/testRest/1" method = "post">
<Input type = "hidden" name = "_ method" value = "PUT"/>
<Input type = "submit" value = "testRestPut"/>
</Form> <br/>
<Form action = "springmvc/testRest/1" method = "post">
<Input type = "hidden" name = "_ method" value = "DELETE"/>
<Input type = "submit" value = "TestRest DELETE"/>
</Form> <br>
<Form action = "springmvc/testRest" method = "post">
<Input type = "submit" value = "testRestPost">
</Form> <br/>
<A href = "springmvc/testRest/1"> testRest </a> <br/>
In addition, we also need to add declarations in the configuration file web. xml that support converting post to delete and put requests.
<! -- Configure HiddenHttpMethodFilter: You can convert a POST request to a DELETE or POST request. -->
<Filter>
<Filter-name> HiddenHttpMethodFilter </filter-name>
<Filter-class> org. springframework. web. filter. HiddenHttpMethodFilter </filter-class>
</Filter>
<Filter-mapping>
<Filter-name> HiddenHttpMethodFilter </filter-name>
<Url-pattern>/* </url-pattern>
</Filter-mapping>
As you can see, the modification and deletion here are both sent through the post method, because put and delete are not supported here for direct deletion, but through the post method, and quietly bring a token of the hidden type input tag to tell the background what I actually sent at the front-end is a request for deletion and modification.
How can this process be implemented? Why?
<input type="hidden" name="_method" value="DELETE"/>
This token will be used by people in the background to buy your account. Then let's look at how we bought it later.
In the final analysis, it still benefits from being added to the web. the HiddenHttpMethodFilter class in xml has a method doFilterInternal in this class. Through debugging, we can find the clues. start tomcat (not tomcat8) and click the input tag corresponding to the delete operation, on the debug page, we can see:
Request. getParameter (this. methodParam) in the request domain to obtain this. the value of methodParam (_ method) corresponds to the delete operation. On the page, delete declares a hidden input, where name is "_ method" and value is DELETE, therefore, the paramValue obtained here is "DELETE"
Continue execution. You can see that the request is passed. whether the value of getMethod is equal to the value of "POST". Obviously, the value here is equal because the method declaration in the delete operation request on the foreground page is post
Then, encapsulate the obtained request method in HttpServletRequest to complete subsequent processing. Here we should understand why the front-end should add such a hidden input.
Trap: Note that the startup cannot be tomcat8, but it can only be a version smaller than 8, such as 7 or 6. It shows the error message of tomcat and the successful response of using 7:
To sum up, how to send put and delete requests:
Configure HiddenHttpMethodFilter in web. xml
Send post request
The request contains a hidden domain named _ mothod and the value is put or delete.
Let's end with the annotation @ CookieValue.
3. @ CookieValue
This annotation is similar and also a ing, which maps to a Cookie value.
When we send a request, we can see that the request carries some cookie values.
For example, JSESSIONID or Path. Now we will write a method to get the Cookie value.
Add
@ RequestMapping (value = "/testCookieValue ")
Public String testCookieValue (@ CookieValue ("JSESSIONID") String cookieValue ){
System. out. println ("testCookieValue:" + cookieValue );
Return SUCCESS;
}
Add link on the index. jsp Interface
<a href="springmvc/testCookieValue">testCookieValue</a><br/><br/>
In this way, we can get a result similar to "testCookieValue: 1410F05C9ADD84E8659C2AC79E8CC666.
So far, we have introduced
@ RequestMapping usage
How to Get @ PathVariable and @ RequestParam of Request Parameters
This section describes how to implement restful requests and analyzes how post is converted to delete and put requests.
Introduced the usage of @ CookieValue
This is the perfect curtain call.-Speak and praise me.
If you have any questions during Java learning or want to obtain some learning resources, you are welcome to join the group's Java learning exchange QQ group: 495273252
Head of Java
No.: javatuanzhang
Sharing Java technical expertise on a daily basis
Long-pressed QR code recognition