resteasy拦截器在preProcess和postProcess之间是否安全?

Tom*_*Tom 5 java multithreading resteasy

如果我有一个实现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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Tom*_*Tom 2

好的,我已经进行了实验,答案似乎是在 JBoss jboss-as-7.1.1.Final 中运行的轻松 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我发现这对于我的使用来说是不够的,因为当出现错误(401、500 等)时不会调用 postProcess,我最终使用了javax.servlet.Filter