【问题标题】:Java Servlet retrieve Spring RequestMapping UrlJava Servlet 检索 Spring RequestMapping Url
【发布时间】:2019-01-08 09:36:07
【问题描述】:

我写了一个请求拦截器来为测试环境中的请求添加一些信息。

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

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

目前我正在检索这样的 URL:

String url = request.getServletPath();

对于这样的控制器:

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

对于像/1/ 这样的请求 url 将是 /1/

有什么办法可以得到 Request-Mapping-Value ==> /{id}

提前致谢

【问题讨论】:

  • id 是一个路径变量,因此如果您在 url 中请求 /1 将是 /1 和 1 ->id 。将“/{id}”更改为“/{id}*”以接受/1、/1/
  • 在拦截器内部我想检索 /{id}/ 作为字符串我不关心 id 本身 (1)
  • 在 preHandle 内部使用 request.getRequestURL().toString() 或 equest.getQueryString() 来检索 /{id}/ 作为字符串
  • getRequestURL 返回完整链接 localhost:8080/1,查询字符串为空但我想要 /{id}
  • 你无法做到这一点,因为 /{id} 你已经在控制器中为路径变量定义了。拦截器拦截您在 url 中传递的任何内容,就像传递 /1 一样,因此它将如何与 {id} 映射。

标签: java spring servlets


【解决方案1】:

@RequestMapping 及其组合注释方法(即@GetMapping@PostMapping 等)由HandlerMethod 处理。因此,将处理程序对象转换为它,您可以访问您想要的 @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);
            }
        } 
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    • 2012-05-23
    • 2017-01-18
    相关资源
    最近更新 更多