Search code examples
javaservletsguiceguice-servlet

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


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?


Solution

  • 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>