Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @RequestMapping

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.

like image 363
user2785929 Avatar asked Oct 28 '13 05:10

user2785929


1 Answers

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.

like image 149
Alex Avatar answered Oct 09 '22 05:10

Alex