Java Servlet检索Spring RequestMapping Url

时间:2019-01-08 09:36:07

标签: java spring servlets

我写了一个请求拦截器,在测试环境中向请求添加一些信息。

public boolean preHandle(HttpServletRequest request,
                         HttpServletResponse response, Object handler)
        throws Exception {
    ...
}

public void postHandle(
        HttpServletRequest request, HttpServletResponse response,
        Object handler, ModelAndView modelAndView)
        throws Exception {
        ...
}

目前,我正在检索如下网址:

String url = request.getServletPath();

对于这样的控制器:

@RequestMapping(value = "/{id}",
        method = RequestMethod.GET)
public ResponseEntity<?> getByID(@PathVariable long ID) {
    ...
}

对于/1/之类的请求 url将是/1/

有什么方法可以获取请求映射值==> /{id}

预先感谢

1 个答案:

答案 0 :(得分:1)

@GetMapping及其组成的注释方法(即@PostMappingHandlerMethod等)由@RequestMapping处理。因此,将处理程序对象投射到该对象上,就可以访问所需的@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler instanceof HandlerMethod) { HandlerMethod hm = (HandlerMethod) handler; RequestMapping mapping = hm.getMethodAnnotation(RequestMapping.class); if (mapping != null) { for(String val : mapping.value()) { //***This is the mapping value of @RequestMapping*** System.out.println(val); } } } } 信息:

{{1}}