问题
I keep seeing this kind of param value = "/redirect/{id}"
in a @RequestMapping
annotation of the Spring. I keep wondering what is {id}
here? Is this some sort of Expression Language
?
Sample code of what I have seen:
@RequestMapping( value = "/files/{id}", method = RequestMethod.GET )
public void getFile( @PathVariable( "id" )
String fileName, HttpServletResponse response )
{
try
{
// get your file as InputStream
InputStream is = new FileInputStream("/pathToFile/"+ fileName);
// copy it to response's OutputStream
IOUtils.copy( is, response.getOutputStream() );
response.flushBuffer();
}
catch( IOException ex )
{
throw new RuntimeException( "IOError writing file to output stream" );
}
}
My question is what is the {id}
in the mapping and what is its relationship with the @PathVariable
annotation and how to use it? I red some info from the web but I will much more appreciate it to hear much more clearer explanation from you guys.
回答1:
The {foo}
part in a @RequestMapping
value is a path variable which means a value retrieved from the url path and not from a request parameter.
For example if the user access to /files/foo.zip
, then {id}
will match foo.zip
and you tell Spring to store that value into the variable that has the annotation @PathVariable("id")
.
You can have multiple path variable in a URL identifier of a @RequestMapping
annotation value, and you can inject these values into a variables by using @PathVariable
with the same id you used inside the curly brackets.
回答2:
I think for your example , by browsing ../files/1 or ../files/2 or ../files/3 , the digits stand for different file name . @PathVariable( "id" ) helps you save time write different parameter function on one purpose.
回答3:
The {id} is the url query string we are passing what ever it may be and retrieving that id with @PathVariable("id") and passing as a argument to the method,one method fits for different requests with changing id here. Thanks.
回答4:
@RequestMapping( value = "/files/{id}", method = RequestMethod.GET )
public void getFile( @PathVariable( "id" ) **String id**)
String fileName, HttpServletResponse response )
{
//your code here
}
pathvariable maps your uri with the method parameter. Here id is what you send with your request eg. /files/7.
来源:https://stackoverflow.com/questions/19627961/spring-requestmapping