我正在编写一个日志记录过滤器,记录在Jersey中运行的Web应用程序的所有HTTP请求/响应.ContainerResponseFilter似乎是一个直接的解决方案,我已设法让它工作.
下一步是记录请求的IP.有没有办法从里面做到这一点ContainerResponseFilter?
zye*_*xal 14
简短回答:
@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 ...
}
}
Run Code Online (Sandbox Code Playgroud)
编辑
(关于希望得到更详细的答案)
Afaig:
该@Context注释允许注入JAX-RS特异性成分(有人可能会说,你是能够注入的上下文信息的对象).JAX-RS本身是基于Java的RESTful Web Services over HTTP协议规范.所以我们可以注入以下内容:
javax.ws.rs.core.UriInfo
javax.ws.rs.core.Request
javax.ws.rs.core.SecurityContext
并且
javax.servlet.http.HttpServletRequest
在Jersey文档的IOC章节中,您将找到以下注释:
[...] Jersey实现允许您直接将HttpServletRequest实例注入到JAX-RS组件中[...] - https://jersey.java.net/nonav/documentation/latest/user-guide.html#d0e2401
[...]特定请求对象存在异常,甚至可以注入构造函数或类字段.对于这些对象,运行时将注入能够同时服务更多请求的代理.这些请求对象是HttpHeaders,Request,UriInfo,SecurityContext.可以使用@Context注释注入这些代理.[...]
[...]使用servlet部署JAX-RS应用程序时,使用@Context可以使用ServletConfig,ServletContext,HttpServletRequest和HttpServletResponse.[...]
如果你这样做,你实际上注入一个名为org.apache.catalina.connector.RequestFacade(链接)的代理.此代理作为您的Coyote(HTTP连接器)的直接热线,从而作为Coyote请求对象(链接).
希望这在某种程度上有所帮助:) - 祝你有愉快的一天.
| 归档时间: |
|
| 查看次数: |
6540 次 |
| 最近记录: |