如果我有一个实现pre和post进程的单一类,我能在preProcess调用和postProcess调用之间存储对象吗?
这真的合法吗?
@ServerInterceptor
@Provider
public class MyInterceptor implements PreProcessInterceptor, PostProcessInterceptor {
private String url;
@Override
public ServerResponse preProcess(HttpRequest request, ResourceMethod resourceMethod) throws Failure, WebApplicationException {
url = request.getUri().getRequestUri().toString();
return null;
}
@Override
public void postProcess(ServerResponse response) {
System.out.println(url);
}
}
答案 0 :(得分:2)
好的,我已经进行了实验,答案似乎是在JBoss jboss-as-7.1.1中运行的简单2.01GA.Final我得到了preProcess和postProcess的不同实例。
所以答案是“这是合法的吗?”是的。
因此,作为一种解决方法,我将包含HttpServletRequest的上下文并将状态存储为请求属性:
@ServerInterceptor
@Provider
public class MyInterceptor implements PreProcessInterceptor, PostProcessInterceptor {
private static final String ATTRIBUTE_NAME = MyInterceptor.class.getName();
@Context
HttpServletRequest servletRequest;
@Override
public ServerResponse preProcess(HttpRequest request, ResourceMethod resourceMethod) throws Failure, WebApplicationException {
String url = request.getUri().getRequestUri().toString();
servletRequest.setAttribute(ATTRIBUTE_NAME, url);
return null;
}
@Override
public void postProcess(ServerResponse response) {
String url = servletRequest.getAttribute(ATTRIBUTE_NAME);
System.out.println(url);
}
}
我找到了我的用途,这是不够的,因为当出现错误(401,500等)时没有调用postProcess,我最终使用javax.servlet.Filter