我正在编写一个日志过滤器,用于记录在 Jersey 中运行的 Web 应用程序的所有 HTTP 请求/响应。 ContainerResponseFilter
似乎是一个直接的解决方案,我已经设法让它工作。
下一步是记录请求的 IP。有没有办法从 ContainerResponseFilter
内部做到这一点?
最佳答案
简短回答:
@Provider
public class YourContextFilter implements ContainerRequestFilter {
@Context
private HttpServletRequest sr;
@Override
public synchronized void filter(ContainerRequestContext request) throws IOException {
/*
* Returns the Internet Protocol (IP) address of the client or
* last proxy that sent the request. For HTTP servlets, same as
* the value of the CGI variable REMOTE_ADDR.
*/
String ip = sr.getRemoteAddr();
// ... log it ...
}
}
<小时/>
编辑
(关于希望获得更详细的答案)
阿费格:
@Context
注释允许注入(inject) JAX-RS –特定组件(有人可能会说你能够注入(inject)上下文信息对象)。 JAX-RS 本身是基于 HTTP 协议(protocol)的 RESTful Web 服务的 Java 规范。所以我们能够注入(inject)类似的东西:
javax.ws.rs.core.UriInfo
javax.ws.rs.core.Request
javax.ws.rs.core.SecurityContext
还有
javax.servlet.http.HttpServletRequest
在 Jersey 文档的国际奥委会章节中,您将找到以下注释:
[...] Jersey implementation allows you to directly inject HttpServletRequest instance into your JAX-RS components [...] - https://jersey.java.net/nonav/documentation/latest/user-guide.html#d0e2401
[...] The exception exists for specific request objects which can injected even into constructor or class fields. For these objects the runtime will inject proxies which are able to simultaneously server more request. These request objects are HttpHeaders, Request, UriInfo, SecurityContext. These proxies can be injected using the @Context annotation. [...]
[...] When deploying a JAX-RS application using servlet then ServletConfig, ServletContext, HttpServletRequest and HttpServletResponse are available using @Context. [...]
如果您这样做,您实际上会注入(inject)一个名为 org.apache.catalina.connector.RequestFacade
( link ) 的代理。该代理充当您与 Coyote(HTTP 连接器)以及 Coyote 请求对象 ( link ) 的直接热线。
希望这对您有所帮助:) - 祝您有美好的一天。
关于jersey - 如何从 ContainerResponseFilter 内部获取源地址/ip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26196298/