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

sto*_*ter 25 spring-mvc

在控制器中,我有这个代码,不知何故,我想得到请求映射值"搜索".这怎么可能 ?

 @RequestMapping("/search/")     
 public Map searchWithSearchTerm(@RequestParam("name") String name) {    
        // more code here     
 }
Run Code Online (Sandbox Code Playgroud)

acd*_*ior 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);

}
Run Code Online (Sandbox Code Playgroud)


Ank*_*sal 23

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

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

  • 假设请求映射类似于 @RequestMapping("/search/{userId}") 在这种情况下,我们将使用 .getServletPath 获取 /search/1 而不是 /search/{id}。关于如何获取 /search/{id} 有什么想法吗? (2认同)

vza*_*llo 13

有像这样的控制器

@Controller
@RequestMapping(value = "/web/objet")
public class TestController {

    @RequestMapping(value = "/save")
    public String save(...) {
        ....
    }
}
Run Code Online (Sandbox Code Playgroud)

你不能使用反射获得控制器基础requestMapping

// Controller requestMapping
String controllerMapping = this.getClass().getAnnotation(RequestMapping.class).value()[0];
Run Code Online (Sandbox Code Playgroud)

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

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

显然可以使用requestMapping单值.

希望这可以帮助.