有没有一种方法可以检查我是否在Guice的servlet请求中?

问题描述:

我正在编写一个JUL日志记录Handler,如果我们当前正在处理请求,我想用有关当前请求的信息来扩充记录的消息.为此,我将Provider<Thing>注入到Handler中,其中Thing@RequestScoped.

I'm writing a JUL logging Handler and I'd like to augment the logged messages with information about the current request, if we're currently handling a request. To accomplish this, I've injected a Provider<Thing> into the Handler, where Thing is @RequestScoped.

但是,如果在我们不处理请求时发生日志记录,则调用provider.get()会引发OutOfScopeException.我觉得赶上OutOfScopeException将是错误的形式.有没有更好的方法来确定请求当前是否正在执行?

However, calling provider.get() throws an OutOfScopeException if the logging happens while we're not handling a request. I feel like catching the OutOfScopeException would be bad form. Is there a better way to determine whether or not a request is currently executing?

通过检票口,我使用了一个小技巧.这应该是独立于框架的.我做了一个请求过滤器,并在其中放置了一个公共的静态ThreadLocal.因此,如果当前线程来自请求,则将设置threadlocal.

With wicket I used a little trick. This should be framework independent. I made a request filter and put a public static ThreadLocal in it. So if current thread is born from request, threadlocal will be set.

public class SessionContext implements Filter {

    private static final ThreadLocal<HttpSession> session = new ThreadLocal<HttpSession>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        return;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        session.set(((HttpServletRequest)servletRequest).getSession());
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        return;
    }

    public static HttpSession getSession(){
        return session.get();
    }

    public static User getUser(){
        return (User) session.get().getAttribute(UserService.USER);
    }
}

和web.xml中的

<filter>
    <filter-name>session</filter-name>
    <filter-class>SessionContext</filter-class>
</filter>