有没有一种方法可以检查我是否在Guice的servlet请求中? [英] Is there a way to check if I'm inside a servlet request with Guice?
问题描述
我正在编写一个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>
这篇关于有没有一种方法可以检查我是否在Guice的servlet请求中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!