我被指定实施一个安全要求,以模仿“类似信使”的身份验证,例如:如果一个用户首先登录,然后另一个用户尝试使用相同的用户名登录,则将提示该新用户“踢”以前的用户登录的用户,系统应使第一个用户的Web会话无效,该Web应用程序在Tomcat 6上运行,我正在查看HTTPSessionContext,但现在已弃用,是否有替代方法,还是我应该自己使用HTTPSessionListener

最佳答案

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);

    }

}

08-17 10:59