Spring @RequestMapping [英] Spring @RequestMapping
问题描述
我一直在 @RequestMapping
中看到这种参数 value =/ redirect / {id}
春天的诠释。我一直在想这里的 {id}
是什么?这是某种表达语言
?
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
?
我所看到的示例代码:
@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
注释的关系以及如何使用它?我从网上获得了一些信息,但是我会更加欣赏你们听到更清楚的解释。
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.
推荐答案
{foo}
部分在 @RequestMapping
值是一个路径变量,表示从url路径检索的值,而不是来自请求参数。
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.
例如,如果用户访问 /files/foo.zip
,则 {id}
将匹配 foo.zip
并告诉Spring将该值存储到具有注释<$ c的变量中$ c> @PathVariable(id)。
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")
.
您可以在 @RequestMapping
注释值,您可以使用 @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.
这篇关于Spring @RequestMapping的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!