Spring @RequestMapping

use*_*929 9 java spring spring-mvc request-mapping

我在春天value = "/redirect/{id}"@RequestMapping注释中一直看到这种格拉姆.我一直想知道{id}这里有什么?这是某种Expression Language吗?

我看到的示例代码:

@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" );
    }

}
Run Code Online (Sandbox Code Playgroud)

我的问题是{id}映射中的内容是什么,它与@PathVariable注释的关系以及如何使用它?我从网上红了一些信息,但是我会更加欣赏它,听到你们更清楚的解释.

Ale*_*lex 14

值中的{foo}部分@RequestMapping是路径变量,表示从URL路径而不是从请求参数检索的值.

例如,如果用户访问/files/foo.zip,则{id}匹配foo.zip并告诉Spring将该值存储到具有注释的变量中@PathVariable("id").

您可以在@RequestMapping注释值的URL标识符中包含多个路径变量,并且可以@PathVariable使用在花括号内使用的相同ID 将这些值注入变量.