对于检票口,我使用了一个小技巧。这应该是独立于框架的。我做了一个请求过滤器并在其中放置了一个公共静态 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>