Spring @RequestMapping

2019-03-16 01:11发布

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.

4条回答
男人必须洒脱
2楼-- · 2019-03-16 01:32

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.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-03-16 01:41

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.

查看更多
Summer. ? 凉城
4楼-- · 2019-03-16 01:45

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.

查看更多
混吃等死
5楼-- · 2019-03-16 01:54
@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.

查看更多
登录 后发表回答