Passing the URI Path to the JAX-RS Providers

北城余情 提交于 2019-12-06 02:07:00

If you want something a bit more JAX-RS specific than HttpServletRequest, you can inject a javax.ws.rs.core.UriInfo.

public class MyProvider implements MessageBodyWriter {
    @javax.ws.rs.core.Context
    javax.ws.rs.core.UriInfo uriInfo;
}

I'm assuming that you're using a @javax.ws.rs.PathParam to capture the path parameter. You can then potentially use UriInfo.getPathParameters(). You can also fall back to UriInfo.getPathSegments() to get the information you're looking for. This saves you the trouble of parsing the request URI yourself. Any JAX-RS implementation should be able to do this.

You can access the URI path from the Provider by defining the @Context annotation on a field on the Provider.

For example,

public class CustomProvider implements MessageBodyWriter
{

    @Context HttpServletRequest request;

    ....
}

This field will automatically be set for each request. Even though the request is set as a field, the value is thread-safe as the actual request is using a proxy and most likely thread local to determine the request that belongs to thread.

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