SPRINGMVC (2) Request Mapping comprehensive analysis

Source: Internet
Author: User

In the SPRINGMVC controller, we often use @requestmapping to complete our request mapping, we can use annotations on the class definition and on the method definition, and its configured path will be the parent path of all methods defined in the class, such as the/user (class) in the previous instance Hello (method).
In general, the path annotations on our class definitions play a role in namespaces, preventing path mappings for different methods from conflicting, for example, I have defined the following methods under Usercontroller and Articlecontroller:

@RequestMapping("list")publicvoidlist(){    ....}

A list mapping path, at which point Springmvc does not know which method to handle the request. Of course, we can also make a two-level path configuration distinction on the method:

/*************UserController***********/@RequestMapping("user/list")publicvoidlist(){    ....}/*************ArticleController***********/@RequestMapping("article/list")publicvoidlist(){    ....}

This will effectively prevent conflicts, but if I have many ways to have such a conflict, do you want to prefix each method? At this point we can choose to annotate @requestmapping on the classpath to differentiate the whole method.

mapping by URL 1. Ant-style character matching

In addition to the standard URLs, the @RequestMapping also supports Ant-style characters, that is, "? , "*", "* *", where
1. "?": Match an arbitrary character, such as/user/a, to match a path such as User/aa,user/ab
2. "*": Match any string, such as/user/a*, to match any path starting with a/user such as/USER/ABC,/USER/AQW, etc.
3. "* *": matching multi-level path string, such as/user/**/list, matching/user/user1/list,/user/1resu/list, etc.

Here, it is important to note that when the position and number of * are different, * can represent a difference in the number of characters , see the following example:

@RequestMapping("u1/*")//can only match u1/a,u1/b, cannot match u1/———— that is, this time * represents one or more characters Public void Test(HttpServletResponse response)throwsioexception{response.getwriter (). Print ("u1/*");}@RequestMapping("u1/**")//able to match U1/,U1/QQ,U1/QQ/WW, it is important to note that "* *" can match 0 and "*" Cannot Public void Test(HttpServletResponse response)throwsioexception{response.getwriter (). Print ("u1/*");}@RequestMapping("u2/a*")//ability to match U2/A,U2/AB,U2/AQQQQ, etc. ———— i.e. * represents 0 or more than 0 characters at this time Public void test1(HttpServletResponse response)throwsioexception{response.getwriter (). Print ("u2/a*");}
2. RESTful placeholder matches

In addition to using the style above, the @RequestMapping also supports the form of a restful style placeholder, and if we need to view its specific article for a particular user, the RESTful style path match looks like this:

@Controller//Note as controller, scanned by spring container, registered as a bean@RequestMapping("/user/{uid}")//One-level access path that takes effect on all methods in the class Public  class usercontroller {    @RequestMapping("Article/{aid}") PublicStringDetail(@pathvariable("UID") Integer uid,@pathvariable("Aid") Integer aid) {SYSTEM.OUT.PRINTLN ("View ID is"+ UID +"User article, and the article ID is"+aid);return "Someplace"; }}

Here, if we want to access a user article with a user ID of 1 and an article ID of 2, you can access the following path: [项目根路径]/user/1/article/2 to complete.
We use @pathvariable ("Val") to complete the resource request for {val} in the corresponding path, where the two Val names need to be consistent, followed by the method into the parameter name arbitrarily, we just example a multipath parameter binding, assuming only one, the following is also legal:

@RequestMapping("user/{uid}")    publicdetail(@PathVariable("uid")Integer notUid){//notUid名字也能成功绑定        return"someplace";    }

In addition, if we have the same name and URL path resource names, we can omit the value values in the configuration @pathvariable, and the following instance can also bind the path resource correctly into the parameter

@RequestMapping("user/{uid}")    publicdetail(@PathVariable Integer uid){//notUid名字也能成功绑定        return"someplace";    }
3. Priority matching Rules

The URL also has the following two common matching criteria: longest and most accurate first match and placeholder first match

1. Longest and most accurate first match

Let's look at a matching instance:

@RequestMapping("test/**") Public void test2(HttpServletResponse response)throwsioexception{response.getwriter (). Print ("test/**");}@RequestMapping("test/*") Public void test3(HttpServletResponse response)throwsioexception{response.getwriter (). Print ("test/*");}@RequestMapping("test/*/**") Public void test4(HttpServletResponse response)throwsioexception{response.getwriter (). Print ("test/*/**");}@RequestMapping("test/*/*") Public void Test5(HttpServletResponse response)throwsioexception{response.getwriter (). Print ("test/*/*");}@RequestMapping("test/1/*") Public void Test6(HttpServletResponse response)throwsioexception{response.getwriter (). Print ("test/1/*");}@RequestMapping("TEST/1/2") Public void Test7(HttpServletResponse response)throwsioexception{response.getwriter (). Print ("TEST/1/2");}

Directly looking at the above match will feel very messy, we directly see the following test:

Test Match Results
test/a 匹配test/*而不匹配test/**(更精确优先匹配)
test/a/a/aa/a 匹配test/**而不匹配test/*/**,(在多层匹配中,**比*/**更精确)
test/a/a 匹配test/*/*,因为/*/*比**精确
test/1/a 匹配test/1/*,因为/1/*比/*/*精确
Test/1/2 匹配test/1/2,这是完全匹配
2. Placeholder first-match principle

Placeholder refers to a path resource placeholder such as @pathvariable, and below we look at an instance

@RequestMapping("TEST/1/2") Public void Test7(HttpServletResponse response)throwsioexception{response.getwriter (). Print ("TEST/1/2");}@RequestMapping("Test/1/{id}") Public void Test8(httpservletresponse response, @PathVariable Integer ID)throwsioexception{response.getwriter (). Print ("test/1/(myid=)"+ ID);}@RequestMapping("test/1/a") Public void Test7(HttpServletResponse response)throwsioexception{response.getwriter (). Print ("test/1/a");}

From all the path mappings of the previous instance, we tested that TEST/1/2 is the most accurate. But we have added a placeholder map, and in the browser input TEST/1/2, this time the browser returns test/1/(myid=) 2, that is, the placeholder has a higher priority than the normal string ! But if we enter test/1/aat this time. The program does not discard the match because of our ID mapping to an integer type in the method in the parameter, the precedence of the placeholder is still higher than the character (string) A, but because "a" cannot be converted to an integer type , the server returns 400 error

Other request resource mappings via HTTP

In addition to using URLs, we can also map through request parameters, request methods, or request headers
Let's take a look at the full list of properties for @requestmapping:

Properties Description
Value Specify the actual address of the request, such as/action/info.
Method Specifies the type of method requested, GET, POST, PUT, delete, and so on
Consumes Specifies the type of submission to process the request (Content-type), such as Application/json, text/html;
Produces Specifies the type of content returned, only if the type in the request header (Accept) contains the specified type to return
Params Specifies that some parameter values must be included in the request for the method to process
Headers Specifies that some specified header values must be included in the request for the method to process requests

Among them, consumes, produces use content-type information to filter information, headers can use Content-type to filter and judge.
In the previous use, we found that the Value property was not specified, and the Value property could be assigned directly to the value attribute in parentheses, because no other attribute in the Java annotations, the direct assignment must be the value member of the annotation, and if the annotation does not have a member named value, an error will be
Let's look at a few examples first:

Example 1:vmethod,headers
@RequestMapping"testa""content-type=text/*")

Indicates that the mapping path is Testa, the request method must be the Post method (if we use post to make the request, an error message is returned, HTTP Status 405-request method ' GET ' not supported), The headers section indicates that the request header information must contain the corresponding part after the equal sign, * match any string

Example 2:consumes
@RequestMapping"testb", consumes="application/json"

Represents a method that matches only requests Content-type to a type of "Application/json".

Example 3:produces
@RequestMapping"/testc", produces="application/json")

A request that represents a method matching requires that the Accept section of the request header contain "Application/json", while in response, the returned content is set to "Application/json"

Example 4:params
@RequestMapping"testd",method = RequestMethod.GET,params = {"id1","id2"})publicvoidtest12throws IOException{    "——" + id2);}

The example indicates that the input parameter must contain two parameters named Id1,id2, if I enter:
1. http://localhost:8080/springMVC/user/testd --
2. http://localhost:8080/springMVC/user/testd?id1=1 -reported 404 errors
3. ttp://localhost:8080/springMVC/user/testd?id1=1&id2=2 --Return to 1--2
4. ttp://localhost:8080/springMVC/user/testd?id1=1&id2=2&id3=3 --Return to 1--2

From the above we can see that only with the corresponding parameters can complete the mapping, and can have other than the requirements of the params parameters, such as ID3.

The common mapping rules for the params are as follows:

Example Rule Description
"Param1" The request must contain a parameter named param1
"!param1" The request cannot contain a parameter named param1
"Param1!=value1 The param1 parameter must be included in the request, but its value cannot be value1
{"Param1=value1", "param2"} The param1 parameter and the param2 parameter need to be included in the request, and the value of param1 must be value1

SPRINGMVC (2) Request Mapping comprehensive analysis

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.