Learn springmvc--how to get request parameters detailed _java

Source: Internet
Author: User
Tags tomcat

@RequestParam, you must have seen @PathVariable, you must know @QueryParam, how could you not know? And you know him (@CookieValue)! She (@ModelAndView)! It (@ModelAttribute)! Yes, just annotating this piece, Spring MVC opens up a colorful world for you. Come, do not hing (mi) Fen, sit down, we have a good chat about all these annotations brothers ~ ~ ~ (wait, have not heard?) All right, come on, you sit in the front row, you! )

First, how does spring MVC match the request path--"request path which strong, requestmapping name spreads"

@RequestMapping are used to map requests, such as GET requests, post requests, or restful and non restful styles. The annotation can be used on a class or method and, if used on a class, represents the parent path of all methods in the class.

Examples (the test classes used here, such as Springmvctest, and some pages are described in the first "learning springmvc--starting from HelloWorld"):

Add test method in 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 to indicate that the method can be positioned through a "/testrequestmapping" relative path. At the same time we also put a class-level requestmapping annotation on the Springmvctest class:

@RequestMapping ("/springmvc")

@Controller public

class Springmvctest { 

Note that a @controller annotation is added here, in Springmvc, which handles the request distributed by Dispatcherservlet, encapsulates the data requested by the user after processing the transaction layer into a model, and then the model Return to the corresponding view for presentation. With a path such as "springmvc/testrequestmapping", we are able to navigate to the Testrequestmapping method and then execute the method body within the method.

To add, requestmapping can implement a fuzzy matching path, such as:

? : Match one character

*: Match any character

* *: Matching multiple paths

/springmvc/**/lasttest can match a path like/springmvc/firsttest/secondtest/lasttest

Second, spring MVC How to get the requested parameters--"Eight Immortals Crossing, recount"

1. @PathVariable

This annotation is used to map the binding placeholders in the request URL. By @pathvariable You can bind the parameters of a placeholder in the URL to the controller of the processing method, do you not understand? See 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:

 
 

We can see that there is a hyperlink, click and then go to the SPRINGMVC/TESTPATHVARIABLE/1 corresponding controller processing method, then we want to get to this request parameter "1", So add "/testpathvariable/id" to the Testpathvariable method, about ID, and the specific corresponding to {ID} in the parameter of the method, through @pathvariable (value= "id") To declare the request parameters to receive and bind and receive through an integer ID. In this way, we can get the front page request parameter "1".

2. @RequestParam

The annotation is also used to get the request parameters. So what's the difference between the annotation and the @pathvariable? Or look at the example:

Adding methods 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 label to index.jsp

 
 

Clicking on the hyperlink on the page will match the requestmapping path on the Testrequestparam method in controller. Note In this method, we declare two variables by @requestparam this annotation to get the parameter values that query takes in the request, one is the username value and the other is the value after the age.

Seeing here, you've probably figured out some of the differences between @pathvariable and @requestparam, and for requests like "SPRINGMVC/TESTPATHVARIABLE/1," We bind the requested arguments through @pathvariable, whereas request parameters such as "springmvc/testrequestparam?username=jackie&age=12" appear as key-value pairs. We use @requestparam to get a specific request value, such as username or age.

There are also Queryparam, which are similar to the Requestparam, because they are not annotations within the Spring MVC framework and are not detailed here.

Spring MVC has a set of solutions for different request types and requests, so let's take a look at what the popular rest-style requests are now--using the rest style to implement additions and deletions.

In the Springmvctest class, the bottom-up implementation of the check (get) Add (POST) Delete (delete) and change (Put) interface

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

} 

Then how to implement the front interface, the corresponding order is

<form action= "SPRINGMVC/TESTREST/1" method= "POST" > <input type= "hidden" name= "_method

  " value= "put" >

  <input type= "Submit" value= "Testrestput"/>

</form><br/><br/>

 

<form action= "SPRINGMVC/TESTREST/1" method= "POST" >

  <input type= "hidden" name= "_method" value= "DELETE"/>

  <input type= "Submit" value= "Testrest DELETE"/>

</form><br><br>

 

<form action= "Springmvc/testrest" method= "POST" >

  <input type= "Submit" value= "Testrestpost" >

</form ><br/><br/>

 

<a href= "SPRINGMVC/TESTREST/1" >testRest</a><br/><br/> 

In addition to this, we also need to add a declaration in the config file web.xml that supports converting post to delete and put requests

<!--configuration Hiddenhttpmethodfilter: can convert post request to 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 changes and deletions here are sent out by post, because there is no support for put and delete to implement the deletion directly, but by means of post, And quietly with a token hidden type of input tag to tell the background I sent in the foreground is actually deleted and changed the request.

So how does this process work, and why do you add

 
 

This token, someone backstage will buy your account. Let's take a look at how we bought it later.

In the final analysis, thanks to the class of Hiddenhttpmethodfilter added in Web.xml, there is a method dofilterinternal in the class, and by debugging we can discover the clue, start Tomcat (not tomcat8), Click the delete operation corresponding input tag, enter the debugging interface, we can see:

    • The value of This.methodparam (_method) in the request field is obtained by Request.getparameter (This.methodparam), which corresponds to the action for deleting the Delete, on the page, Delete declares a hidden input, where name is "_method" and value is delete, so the Paramvalue value here is "Delete"
    • To continue, you can see whether the value passed by Request.getmethod is equal to "post", and obviously, this is equal, because we declare the method as POST in the action request for delete in the foreground page.
    • In the future, the acquired request method is encapsulated in HttpServletRequest to complete the subsequent processing. Here we should understand why the front desk should add such a hidden input.

Small pits: Here Notice that the boot can not be tomcat8, and can only be smaller than 8 version, such as 7 or 6, and so on, the following figure shows the error message with Tomcat and 7 successful response:

In summary, how to send the put and delete requests:

1. Configure Hiddenhttpmethodfilter in Web.xml

2. Send POST request

3. The request is a hidden field, name is "_mothod", value is put or delete

Finally, next @cookievalue this annotation.

3. @CookieValue

The annotation is also similar to the same routine and is a mapping that maps to a cookie value.

When we send a request, we can see that the request carries some cookie value

such as the jsessionid here or path. Now we're going to write a method to get the cookie value.

Add in Springmvctest

@RequestMapping (value= "/testcookievalue") public

string Testcookievalue (@CookieValue ("Jsessionid") string Cookievalue) {

  System.out.println ("Testcookievalue:" + cookievalue);

  return SUCCESS;

} 

Add links to the Index.jsp interface

 
 

So we can get a result like "testcookievalue:1410f05c9add84e8659c2ac79e8cc666".

So far, we have introduced

1. Use of @RequestMapping

2. Get the @pathvariable, @RequestParam usage of request parameter

3. Describes how to implement a restful request and analyze how post translates to delete and put requests

4. Introduced the usage of @cookievalue

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.