java - 如何检索 tomcat 实例中的 Activity session ?

标签 java tomcat session

我被指定实现一个安全要求来模仿“像信使一样”的身份验证,例如:如果一个用户第一次登录,然后另一个用户试图用相同的用户名登录,这个新用户将被提示“踢“之前登录的用户和系统应该使第一个用户的网络 session 无效,网络应用程序在 tomcat 6 上运行,我正在查看 HTTPSessionContext但它现在已被弃用,是否有替代方案或者我应该自己使用 HTTPSessionListener 实现一些东西? ?

最佳答案

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

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

    }

}

关于java - 如何检索 tomcat 实例中的 Activity session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3515209/

相关文章:

java - prunsrv.exe 服务未启动

Spring flash 属性在反向代理后面不起作用

java - 在 mac 上使用 tomcat 8 在 eclipse 中运行 Web 应用程序

java - Hibernate 一级和二级缓存如何与多个 session 一起工作

java - 将集合 A 复制到集合 B 并包含集合 A 的子类?用于接受在线订单。 java

java - Java 中的线程未恢复?

session - AddDistributedSqlServerCache 没有将 session 保存到数据库中

javascript - PHP - 语言切换 - MVC 框架 - 基于 session 或 Javascript(i18next 库)?什么更好?

java - 使用 String 嵌套 for 循环

java - 如何拒绝来自 iframe 的站点访问?