9

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.

Aniket Kulkarni
  • 12,825
  • 9
  • 67
  • 90
user2785929
  • 985
  • 7
  • 13
  • 30

4 Answers4

14

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.

Alex
  • 25,147
  • 6
  • 59
  • 55
  • how about `/file/x=y` does the annotation will save `x`? – user2785929 Oct 28 '13 at 06:20
  • 1
    No, if you want `x=y` you need to pass it like `/file/?x=y` and use a `@RequestParam("x") String x` that will correctly hold the value `y` – Alex Oct 28 '13 at 08:25
0

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.

soniccol
  • 23
  • 6
0

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.

0
@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.

Ean V
  • 5,091
  • 5
  • 31
  • 39
anshu
  • 1