如果该URL包含路径变量,有没有办法在ServletRequest中找到确切的请求URL?

时间:2018-06-12 07:55:00

标签: java spring-mvc spring-boot servlet-3.0

例如,如果我在调用/app/service/{id}时将我的网址映射到request.getRequestURI(),则会以我在控制器类中指定的相同格式向我提供类似/app/service/10的内容。有没有办法实现同样的目标?

3 个答案:

答案 0 :(得分:1)

如果您使用HttpServletRequest request

你可以使用
    request.getRequestURL();

或者你可以使用

String path = request.getPathInfo();
String[] pathParts = pathInfo.split("/");

答案 1 :(得分:0)

Asumming你正在使用HttpServletRequest request

request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)

答案 2 :(得分:0)

我使用的是Filter,使用HandlerInterceptor为我工作。所以我之前的代码是

public class MyInterceptor implements Filter {

    @Override
    public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) 
               throws IOException, ServletException {
                 final HttpServletRequest req = (HttpServletRequest) request;
                 String url = req.getRequestURI();
                //this was giving me /app/service/10
        }

现在我已将代码更改为

 public class MyInterceptor implements HandlerInterceptor {

        @Override
        public boolean preHandle( HttpServletRequest request, HttpServletResponse response, Object handler )
                throws Exception
        {
           String url = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
          //this gives me /app/service/{id}
        }

    }