我有一个页面,可以访问具有Alpha权限的帐户。 JSP在会话中检查名为"AlphaPerm"的属性。

但是,我遇到的问题是,如果我发现用户在混乱/滥用Alpha测试权限,我想立即阻止他。我可以立即在数据库中更改他的权限,但这并不能立即阻止滥用者。

一种可能的解决方案是每次用户执行某项操作时都检查我的数据库,但是我不想这样做,因为这会使数据库变慢。

那么,如何即时终止他的会话(我的计划是创建管理页面,但如何获取用户会话对象)?基本上,我想创建一个管理页面,以便可以禁止用户。

最佳答案

您可以通过实现HttpSessionListener保留对用户会话的引用。 This example显示了如何实现会话计数器,但是您也可以通过将单个会话的引用存储在上下文范围内的集合中来保留它们。然后,您可以从管理页面访问会话,检查其属性并使其中一些无效。 This post可能还有有用的信息。

编辑:这是一个示例实现(未测试):

public class MySessionListener implements HttpSessionListener {

    static public Map<String, HttpSession> getSessionMap(ServletContext appContext) {
        Map<String, HttpSession> sessionMap = (Map<String, HttpSession>) appContext.getAttribute("globalSessionMap");
        if (sessionMap == null) {
            sessionMap = new ConcurrentHashMap<String, HttpSession>();
            appContext.setAttribute("globalSessionMap", sessionMap);
        }
        return sessionMap;
    }

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        Map<String, HttpSession> sessionMap = getSessionMap(event.getSession().getServletContext());
        sessionMap.put(event.getSession().getId(), event.getSession());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        Map<String, HttpSession> sessionMap = getSessionMap(event.getSession().getServletContext());
        sessionMap.remove(event.getSession().getId());
    }
}


然后,您可以从任何servlet访问会话映射:

Collection<HttpSession> sessions = MySessionListener.getSessionMap(getServletContext()).values();

07-27 18:30