Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Values in braces in Spring Annotations

This might be a simple question for those who know Spring, but since I am a newbie, I will ask it anyway.

I am going through some Spring code and I am not able to understand the following-

 @RequestMapping(value="/{id}") 
 public void show(@PathVariable("id") long id, Model model) {...}

The comment for this section of the code is - "When using URI Templates, access parameters using the @PathVariable annotation.

Now earlier, I came across code like

 @RequestMapping(value="/url/path") 
 public String list(Model model) {...}

By this, I understand that whenever the url "/url/path" is encountered, the list() method will be called, but I am not able to make sense of the former annotation. What does it mean?

Also, the next line says @PathVariable annotations can be limited via regular expressions

 @RequestMapping(value="/{id}")
 public void show(@PathVariable("id:[\\d]*") String idl) {...} // will match only numberic IDs

What does it mean?

like image 810
CodeBlue Avatar asked Jan 29 '26 14:01

CodeBlue


1 Answers

16.3.2.2 URI Template Patterns

URI templates can be used for convenient access to selected parts of a URL in a @RequestMapping method.

For example, the URI Template http://www.example.com/users/{userId} contains the variable userId. Assigning the value fred to the variable yields http://www.example.com/users/fred.

In Spring MVC you can use the @PathVariable annotation on a method argument to bind it to the value of a URI template variable:

So, in your example:

@RequestMapping(value="/{id}") 
public void show(@PathVariable("id") long id, Model model) {...}

This will extract the part of the URL represented by {id}, and bind it to the id method parameter, e.g. the path /42 will bind 42 to id.

like image 88
skaffman Avatar answered Feb 01 '26 14:02

skaffman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!