簡體   English   中英

登錄后創建新會話

[英]create new session after login

我編寫了一個過濾器,該過濾器應在登錄后創建一個新會話以修復會話固定。 僅當用戶登錄系統時才應調用此方法:

//variables
public class GenerteNewSessionFilter implements Filter {

    public static final String NEW_SESSION_INDICATOR = "cab";

    // destroy
    public void destroy() {
        // TODO Auto-generated method stub

    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        if (httpRequest.getSession(false) != null && httpRequest.getSession(false).getAttribute(NEW_SESSION_INDICATOR) != null) {

            // copy session attributes from new session to a map.
            HttpSession session = httpRequest.getSession();

            // HashMap old = new HashMap();
            HashMap<String, Object> old = new HashMap<String, Object>();
            Enumeration keys = (Enumeration) session.getAttributeNames();
            while (keys.hasMoreElements()) {
                String key = (String) keys.nextElement();
                if (!NEW_SESSION_INDICATOR.equals(key)) {
                    old.put(key, session.getAttribute(key));
                    session.removeAttribute(key);
                }
            }

            // invalidation session and create new session.
            session.invalidate();
            session = httpRequest.getSession(true);

            // copy key value pairs from map to new session.
            for (Map.Entry entry : old.entrySet()) {
                session.setAttribute((String) entry.getKey(), entry.getValue());
            }
        }
    }

    // initiatiliazion
    public void init(FilterConfig filterConfig) throws ServletException {

    }
}

但是我只想在用戶登錄到應用程序時執行一次,請指導我如何實現它。

謝謝。

您可以將過濾器應用於特定的servlet。 因此,僅將其應用於處理LoginAction的servlet,這樣,只有在用戶登錄時才執行。

在您的web.xml只需更改過濾器路徑即可。
將您的<url-pattern>更改為servlet的相同路徑。

<filter>
    <display-name>SessionFilter</display-name>
    <filter-name>SessionFilter</filter-name>
    <filter-class>com.session.SessionFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>NewSessionFilter</filter-name>
    <url-pattern>/your/path/LoginAction</url-pattern>
</filter-mapping>

或者使用<servlet-name>而不是<url-pattern>

<filter-mapping>
    <filter-name>SessionFilter</filter-name>
    <servlet-name>LoginAction</servlet-name>
</filter-mapping>

注意,您也可以將<ulr-pattern>應用於您的jsp。
<url-pattern>/your/path/login.jsp</url-pattern>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM