Is there a way to check if I'm inside a servlet request with Guice?

回眸只為那壹抹淺笑 提交于 2020-01-05 03:32:14

问题


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.

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?


回答1:


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);
    }
}

and in web.xml:

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



回答2:


As far as I know, there is no elegant way to do this. The Guice API is tight and will not grant access to the thread-local needed to make such a test. As of version 3, the thread-local in question sits on com.google.inject.servlet.GuiceFilter#localContext. You could access it by reflection but it is arguably even worse style than catching the exception.

I would stick on caching the exception... or hack into that class and add an static boolean test method.



来源:https://stackoverflow.com/questions/17303134/is-there-a-way-to-check-if-im-inside-a-servlet-request-with-guice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!