【问题标题】:Any way to get the path parameters in httpservlet request在 httpservletrequest 中获取路径参数的任何方式
【发布时间】:2014-04-07 15:12:21
【问题描述】:

我已经实施了休息服务。

我正在尝试在过滤器中获取请求的路径参数。

我的要求是

/api/test/{id1}/{status}

 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException
    {
         //Way to get the path parameters id1 and status


     }

【问题讨论】:

    标签: rest servlets jersey path-parameter


    【解决方案1】:

    除了尝试自己解析 URI 之外,没有其他方法可以在 ServletFilter 中执行此操作,但如果您决定使用 JAX-RS 请求过滤器,则可以访问路径参数:

    @Provider
    public class PathParamterFilter implements ContainerRequestFilter {
    
        @Override
         public void filter(ContainerRequestContext request) throws IOException {
            MultivaluedMap<String, String> pathParameters = request.getUriInfo().getPathParameters();
            pathParameters.get("status");
            ....
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以在过滤器中自动装配 HttpServletRequest 并使用它来获取信息。

      @Autowire
      HttpServletRequest httpRequest
      
      
      httpRequest.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE)  
      
      will give you map of path params.
      

      例子:

      如果您的请求类似于 url/{requestId} 那么上面的地图将返回

      0 = {LinkedHashMap$Entry@12596} "requestId" -> "a5185067-612a-422e-bac6-1f3d3fd20809"
       key = "requestId"
       value = "a5185067-612a-422e-bac6-1f3d3fd20809"
      

      【讨论】:

      • 但请注意,这需要运行一些过滤器才能使用!
      • 有什么例子吗?
      【解决方案3】:
      String pathInfo = request.getPathInfo();
          if (pathInfo != null) {
              String[] parts = pathInfo.split("/");
              int indexOfName = Arrays.asList(parts).indexOf("test");
              if (indexOfName != -1) {
                  Optional<String> testId1 = Optional.of(parts[indexOfName + 1]);
                  Optional<String> status= Optional.of(parts[indexOfName + 2]);
              }
      
          }
      

      你的 Servlet 映射应该是到 /api/* 例如。 @WebServlet(urlPatterns = {"/api/*"})

      【讨论】:

        猜你喜欢
        • 2011-10-07
        • 1970-01-01
        • 1970-01-01
        • 2014-06-15
        • 1970-01-01
        • 1970-01-01
        • 2018-01-10
        • 2022-11-03
        • 2019-01-24
        相关资源
        最近更新 更多