SpringBoot – @ PathVariable

The URL variable

Urls in Web applications are often unchangeable. For example, two personal homepages of weibo users correspond to two different urls: weibo.com/user1 and weibo.com/user2. We can’t write a @requestMapping annotated method for every user to handle their requests, that is, for urls with the same pattern (for example, different users’ home pages, they are only part of the URL, for their respective usernames, we say they have the same pattern).

Define URL variable rules

You can use {} in the @requestMapping annotation to indicate its variable parts, for example:

@RequestMapping(value="/user/{username}")
Copy the code

{username} is the name of the variable, so this URL route can match any of the following urls:

  • /user/Tom
  • /user/Jerry
  • /user/Jack2

Note that by default, variables cannot contain the URL separator /, for example, routes cannot match /user/Denny/Jon, even if you think Denny/Jon is an existing user name.

Get URL variable

After we define the variable rule in the route, we usually need to get the value of the URL in the processing method (i.e. the @requestMapping annotation method) and do the corresponding operation based on the value (e.g. the user name). SpringMVC provides @pathVariable to help us:

 
Copy the code
  1. @RequestMapping(value="/user/{username}")
  2. public String userProfile(@PathVariable(value="username") String username) {
  3. return "user"+username;
  4. }

In the example above, when @Controller processes the HTTP request, the userProfile parameter username is automatically set to the value of the corresponding variable username (named assignment) in the URL. For example, when the HTTP request is /user/ FPC, the value of the URL variable username, FPC, is assigned to the function parameter username, and the function returns the value userfpc.

By default, Spring automatically assigns values to variables annotated by @pathVariable. It can also specify which URL variables to use for @pathVariable:

 
Copy the code
  1. @RequestMapping(value = "user/{username}")
  2. public String userProfile(@PathVariable(value="username") String username) {
  3. return "user"+username;
  4. }

Running results:

Define multiple URL variables

You can define a URL route that contains multiple URL variables:

 
Copy the code
  1. @RequestMapping(value = "/user/{username}/blog/{blogId}")
  2. public String getUserBlog(@PathVariable String username, @PathVariable int blogId) {
  3. return "user:" + username + "blog->" + blogId;
  4. }

In this case, Spring can automatically assign the corresponding function parameter value based on the name, and of course can explicitly indicate the specific URL variable value in @pathVariable.

By default, @pathVariable annotations can take arguments of basic simple types: int, long, Date, String, etc. Spring can convert them based on the URL variable value and function parameter type. For example, /user/ FPC /blog/1 assigns the value of FPC to username and 1 to the int variable blogId.

Running results:

Matching regular expressions

Many times, URL variables need to be defined more precisely. For example, the username may contain only upper and lower case letters, numbers, and underscores, and we want:

  • /user/ FPC is a valid URL
  • /user/#$$$is an invalid URL

In addition to simply defining the {username} variable, you can define regular expressions for more precise control, with the syntax {variable name: regular expression}. [A-zA-z0-9_]+ is a regular expression that can contain only lowercase letters, uppercase letters, digits, and underscores (_). After setting the URL variable rule, invalid urls are not processed and the SpringMVC framework returns 404NotFound.

@RequestMapping(value = "/user/{username: [a-zA-Z0-9]+}/blog/{blogId}")
Copy the code

 

SpringBoot – @ RequestParam

Request parameters

When visiting various websites, it is common to find that the last part of the URL looks like:? Xx = yy&zz = ww. This is the Request parameter in the HTTP protocol. What does it do? Let’s start with an example:

  • Search the Web in Zhihu
  • When the browser switches to the new page, the URL is www.zhihu.com/search?type…
  • Search for Java in Zhihu
  • When the browser switches to the new page, the URL is www.zhihu.com/search?type…

In this case, type=content&q=web is the parameter of the search request. Different parameters are separated by &. Each parameter is in the form of name=value, representing the parameter name and value respectively. In this example, we enter different search terms, and the Q parameter of the URL on the search results page is different. That is, HTTP parameters can actually be thought of as user input, and the server returns different output based on the user input (for example, a search for Spring and a search for Java will show different results).

The Request parameter in Spring MVC

In the SpringMVC framework, URL requests can be handled by defining @RequestMapping. Just like @pathvariable, you need to get the parameters in the URL in the function that handles the URL, which is? Key1 =value1&key2=value2. The @requestParam annotation makes it easy to bind parameters in the URL to variables in the handler function method:

 
Copy the code
  1. @RequestMapping(value="/user")
  2. public String getUserBlog(@RequestParam(value="id") int blogId) {
  3. return "blogId="+blogId;
  4. }

So, when we access /user/? With id=123, SpringMVC helps us bind the value of the Request parameter ID to the handler parameter blogId. This makes it easy to take user input, evaluate and return it based on its value.

Running results:

 

@ RequestParam and @ PathVariable

Similarities and differences

Both @requestParam and @PathVariable can do something similar — because they are essentially user input in different parts, one in the URL path part and the other in the parameters part. To access a blog post, both URL designs are possible:

  • Via @pathvariable, such as /blogs/1
  • Via @requestParam, such as blogs? blogId=1

So which one should you choose? Advice:

1. Use @pathVariable when the URL points to a specific business resource (or list of resources), such as a blog or a user

2. Use @requestParam when a URL needs to filter resources or resource lists

For example, we would design the URL like this:

  • /blogs/{blogId}
  • /blogs? State =publish instead of /blogs/state/publish to indicate blog posts in the published state

More usage

Once we define the @requestParam variable in the method, we will throw an exception if the URL is accessed without the corresponding parameter — this is obvious, and Spring tried to bind it for us, but failed. Sometimes, however, the parameter does not always exist. In this case, we can define the required attribute:

@RequestParam(value = "id", required = false)
Copy the code

Of course, in cases where no argument exists, you might want the variable to have a default value:

@RequestParam(value = "id", required = false, defaultValue = "0")
Copy the code