Spring @RequestMapping

时间:2013-10-28 05:52:03

标签: 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" );
    }

}

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

4 个答案:

答案 0 :(得分:14)

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

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

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

答案 1 :(得分:0)

我认为对于您的示例,通过浏览../files/1或../files/2或../files/3,数字代表不同的文件名。 @PathVariable(“id”)可以帮助您节省编写不同参数函数的时间。

答案 2 :(得分:0)

{id}是我们正在传递的url查询字符串,并使用@PathVariable(“id”)检索该id并作为参数传递给方法,一种方法适合于更改id的不同请求这里。 感谢。

答案 3 :(得分:0)

@RequestMapping( value = "/files/{id}", method = RequestMethod.GET )
public void getFile( @PathVariable( "id" ) **String id**)
String fileName, HttpServletResponse response )
{
    //your code here
}

pathvariable使用method参数映射你的uri。这里的id是你发送的请求,例如。 /文件/ 7。