隨着檢票口我用了一個小技巧。這應該是框架獨立的。我做了一個請求過濾器,並在其中放置了一個公共靜態的ThreadLocal。所以如果當前線程是從請求中產生的,threadlocal將被設置。
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>
這是個好主意!實際上,你甚至不用慌亂web.xml,你可以使用'filter(「/ *」)。(MyFilter.class)'語法:https://code.google.com/p/谷歌 - 吉斯/維基/的servlet#Filter_Mapping –