以何种方式获取httpservlet请求中的路径参数

Pat*_*tan 4 rest servlets jersey path-parameter

我已经实施了休息服务.

我试图在过滤器中获取请求的路径参数.

我的要求是

/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


     }
Run Code Online (Sandbox Code Playgroud)

Viv*_*arg 11

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

@Autowire
HttpServletRequest httpRequest


httpRequest.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE)  

will give you map of path params.
Run Code Online (Sandbox Code Playgroud)

例:

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

0 = {LinkedHashMap$Entry@12596} "requestId" -> "a5185067-612a-422e-bac6-1f3d3fd20809"
 key = "requestId"
 value = "a5185067-612a-422e-bac6-1f3d3fd20809"
Run Code Online (Sandbox Code Playgroud)

  • 但请注意,这需要运行一些过滤器才能使用! (2认同)
  • 有这样的例子吗? (2认同)

jko*_*acs 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");
        ....
    }
}
Run Code Online (Sandbox Code Playgroud)