如何在控制器中获取请求映射值?

时间:2010-09-26 04:00:36

标签: spring-mvc

在控制器中,我有这个代码, 不知何故,我想获取请求映射值“搜索”。 怎么可能?

 @RequestMapping("/search/")     
 public Map searchWithSearchTerm(@RequestParam("name") String name) {    
        // more code here     
 }

4 个答案:

答案 0 :(得分:24)

如果您需要该模式,可以尝试HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE

@RequestMapping({"/search/{subpath}/other", "/find/other/{subpath}"})
public Map searchWithSearchTerm(@PathVariable("subpath") String subpath,
                                             @RequestParam("name") String name) {

    String pattern = (String) request.getAttribute(
                                 HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
    // pattern will be either "/search/{subpath}/other" or
    // "/find/other/{subpath}", depending on the url requested
    System.out.println("Pattern matched: "+pattern);

}

答案 1 :(得分:20)

看来你正在寻找这个请求匹配的路径,然后你可以直接从servlet路径获取它

@RequestMapping("/search/")     
 public Map searchWithSearchTerm(@RequestParam("name") String name, HttpServletRequest request) {    
String path = request.getServletPath();
        // more code here     
 }

答案 2 :(得分:11)

拥有像

这样的控制器
@Controller
@RequestMapping(value = "/web/objet")
public class TestController {

    @RequestMapping(value = "/save")
    public String save(...) {
        ....
    }
}

您无法使用反射获取控制器基础requestMapping

// Controller requestMapping
String controllerMapping = this.getClass().getAnnotation(RequestMapping.class).value()[0];

或方法requestMapping(来自方法内部)也带有反射

//Method requestMapping
String methodMapping = new Object(){}.getClass().getEnclosingMethod().getAnnotation(RequestMapping.class).value()[0];

显然适用于requestMapping单值。

希望这有帮助。

答案 3 :(得分:2)

@RequestMapping("foo/bar/blub")     
public Map searchWithSearchTerm(@RequestParam("name") String name, HttpServletRequest request) {
  // delivers the path without context root 
  // mapping = "/foo/bar/blub"
  String mapping = request.getPathInfo();
  // more code here
}