Any way to get the path parameters in httpservlet request

家住魔仙堡 提交于 2019-12-06 05:51:09

问题


I have rest service implemented.

I am trying to get the path parameters of the the request in filter.

My request is

/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


     }

回答1:


There's no other way to do it in a ServletFilter other than trying to parse the URI yourself, but you can access the path parameters if you decide to use a JAX-RS request filter:

@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:


You can autowire HttpServletRequest in your filter and use it to get information.

@Autowire
HttpServletRequest httpRequest


httpRequest.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE)  

will give you map of path params.

Example:

If your request is like url/{requestId} then above map will return

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


来源:https://stackoverflow.com/questions/22199830/any-way-to-get-the-path-parameters-in-httpservlet-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!