当我将多个值映射到@RequestMapping(如Multiple Spring @RequestMapping annotations)时,我可以获取请求的值(URL)吗?
像这样:
@RequestMapping(value={"/center", "/left"}, method=RequestMethod.GET)
public String getCenter(Model model) throws Exception {
String requestedValue = getRequestedValue(); // I want this.
// I want to do something like this with requested value.
String result;
if (requestedValue.equals("center")
result = "center";
else if (requestedValue.equals("left")
result = "left";
return result;
}
答案 0 :(得分:17)
您可以将请求(HttpServletRequest
)本身作为处理程序方法的参数。因此,您可以检查请求网址以获取“值”。
@RequestMapping(value={"/center", "/left"}, method=RequestMethod.GET)
public String getCenter(Model model, HttpServletRequest request) throws Exception {
String whatYouCallValue = request.getServletPath();
....
顺便说一句:当我理解你的时候,你想拥有不同的网址,而不是不同的价值。
答案 1 :(得分:6)
从Spring 3.1.0开始,您可以使用URI Template Patterns with Regular Expressions。
@RequestMapping(value={"/{path:[a-z-]+}"}, method=RequestMethod.GET)
public String getCenter(@PathVariable String path) throws Exception {
// "path" is what I want
}
答案 2 :(得分:1)
使用RequestParam注释。您还可以在方法中添加HttpServletRequest类型的参数,然后从中添加getParameters。
答案 3 :(得分:1)
从Spring 3.1.0开始,您可以使用ServletUriComponentsBuilder
@RequestMapping(value={"/center", "/left"}, method=RequestMethod.GET)
public String getCenter(Model model) throws Exception {
UriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentRequest();
String requestedValue = builder.buildAndExpand().getPath(); // I want this.
System.out.println(requestedValue);
// I want to do something like this with requested value.
String result="fail";
if (requestedValue.equals("center"))
result = "center";
else if (requestedValue.equals("left"))
result = "left";
return result;
}
答案 4 :(得分:0)
除了最好的答案@Hugh_Lee: 此方法适用于所有未映射的请求。如果您只想在两个(或几个)情况下使用此方法,例如" /中心"和" / left",你可以做以下。重命名" center" to" positionCenter"," left"到" positionLeft" (或添加另一个常用词)。所以代码就像这样:
@RequestMapping(value={"/{path:position+[A-Za-z-]+}"}, method=RequestMethod.GET)
public String getCenter(@PathVariable String path) throws Exception {
// "path" is what I want
}
答案 5 :(得分:0)
以下正则表达式会使您的方法仅针对网址/center
和/left
执行。您可以使用@PathVariable
注释获取值。
@GetMapping("/{path:^center$|^left$}")
public ResponseEntity<?> whatIsThePath(@PathVariable String path){
// path is either "center" or "left"
}