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?
16.3.2.2 URI Template Patterns
URI templates can be used for convenient access to selected parts of a URL in a
@RequestMappingmethod.For example, the URI Template
http://www.example.com/users/{userId}contains the variableuserId. Assigning the valuefredto the variable yieldshttp://www.example.com/users/fred.In Spring MVC you can use the
@PathVariableannotation 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With