如果我有一个同时实现前处理和后处理的类,是否可以将对象存储在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);
}
}
最佳答案
好的,我已经进行了实验,答案似乎是,在JBoss jboss-as-7.1.1.Fine中轻松运行的2.01GA中,最终我获得了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