我在
Spring的@RequestMapping注释中看到这种param value =“/ redirect / {id}”.我一直想知道这里的{id}是什么?这是某种表达语言吗?
我看到的示例代码:
@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" );
}
}
我的问题是映射中的{id}是什么,它与@PathVariable注释的关系以及如何使用它?我从网上红了一些信息,但我会更加欣赏,听到你们更清楚的解释.
解决方法
@RequestMapping值中的{foo}部分是一个路径变量,表示从url路径检索的值,而不是请求参数.
例如,如果用户访问/files/foo.zip,则{id}将匹配foo.zip,并告诉Spring将该值存储到具有注释@PathVariable(“id”)的变量中.
您可以在@RequestMapping注释值的URL标识符中具有多个路径变量,并且可以通过使用与大括号内使用相同id的@PathVariable将这些值注入到变量中.