10

我已经实施了休息服务。

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

我的要求是

/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


     }
4

3 回答 3

24

您可以在过滤器中自动装配 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"
于 2018-07-27T06:15:25.973 回答
5

除了尝试自己解析 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");
        ....
    }
}
于 2014-03-07T16:16:02.197 回答
-1
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/*"})

于 2020-08-25T20:09:20.233 回答