如何在tomcat实例中检索活动会话?

时间:2010-08-18 18:11:30

标签: java tomcat session

我被指定实施安全要求以模仿“信使类似”身份验证,例如:如果用户首次登录,则另一个用户尝试使用相同的用户名登录,此新用户将被提示“踢” “以前的用户和系统应该使第一个用户的网络会话无效,网络应用程序在tomcat 6上运行,我正在查看HTTPSessionContext,但现在已经弃用,是否有替代方案或我应该去使用HTTPSessionListener来实现自己的东西?

1 个答案:

答案 0 :(得分:0)

HTTPSessionListener可能无法正常工作,因为您无法访问那里的用户主体。我使用过滤器做了类似的事情(没有会话失效)。这是我用一些可能适用于您的情况的代码所做的条带化版本(尚未测试):

public class ApplicationFilter implements Filter {

    private Map<String, HttpSession> sessions = new HashMap<String, HttpSession>();

    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) 
        throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        Principal principal = request.getUserPrincipal();
        HttpSession session = request.getSession();

        if (principal != null && session.getAttribute("THE_PRINCIPAL") == null) {

            // update the current session
            session.setAttribute("THE_PRINCIPAL", session);

            // get the username from the principal
            // (assumes you using container based authentication)
            String username = principal.getName();

            // invalidate previous session if it exists
            HttpSession s = sessions.get(username);
            if (s != null)
                s.invalidate();

            // register this session as the one for the user
            sessions.put(username, session);

        }

        chain.doFilter(servletRequest, servletResponse);

    }

}