cww*_*cww 49 java api jax-rs jax-ws jersey
我已经在一年中的大部分时间里使用了泽西,并且偶然发现了一个我无法找到答案的问题:你如何拦截(或挂钩)泽西岛请求生命周期?
理想情况下,我可以在容器接受来自网络的请求和调用处理程序方法的时间之间执行一些自定义过滤/验证/拒绝.如果有一种通过子路径过滤拦截器的简单方法(例如,对于/下的任何内容都有一个拦截器,对于/ user /下的任何东西,等等),可以获得奖励积分.
谢谢!
编辑:为了更清楚一点,这里的一般想法是能够编写一些将为许多API调用运行的代码,而无需从每个处理程序方法显式调用该代码.这将减少额外的代码并消除传递请求上下文的需要.
cww*_*cww 51
我找到了答案.
首先,创建一个实现ContainerRequestFilter的类.接口指定以下方法,其中进行过滤.ContainerRequest对象包含有关当前请求的信息.
public ContainerRequest filter(ContainerRequest req);
Run Code Online (Sandbox Code Playgroud)
之后,在web.xml中的servlet配置中包含以下XML
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
<param-value>path.to.filtering.class</param-value>
</init-param>
Run Code Online (Sandbox Code Playgroud)
资料来源:
http://jersey.576304.n2.nabble.com/ContainerRequestFilter-and-Resources-td4419975.html http://markmail.org/message/p7yxygz4wpakqno5
这个帖子有点旧,但我在请求之前和之后都有一段时间拦截.经过长时间的网络搜索后,我终于弄明白了:
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>blah.LoggingFilter</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
<param-value>blah.LoggingFilter</param-value>
</init-param>
Run Code Online (Sandbox Code Playgroud)
然后这个班:
public class LoggingFilter extends LoggingFilter implements ContainerRequestFilter {
private static final ThreadLocal<Long> startTime = new ThreadLocal<Long>();
public static boolean verboseLogging = false;
@Override
public ContainerRequest filter(ContainerRequest arg0) {
startTime.set(System.currentTimeMillis());
return arg0;
}
@Override
public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
System.out.println(System.currentTimeMillis() - startTime.get().longValue());
StringBuilder sb = new StringBuilder();
sb.append("User:").append((request.getUserPrincipal() == null ? "unknown" : request.getUserPrincipal().getName()));
sb.append(" - Path:").append(request.getRequestUri().getPath());
//...
}
Run Code Online (Sandbox Code Playgroud)
这会在开始和结束时截取请求,以便您可以输入计时器或其他任何内容.
这适用于Jersey 1.17.关于2.x不确定.