[英]Servlets and session
考慮servlet A將用戶綁定到這樣的會話:
HttpSession session = req.getSession(true);
並且該用戶不久之后對屬於servelt A的同一應用程序的servlet B執行請求。
此時 servlet B 執行時:
HttpSession session = req.getSession(false);
會話是否為空?
以下是此代碼返回 null 的可能原因:
如有必要,為該請求創建一個新會話為true
; false
返回NULL如果沒有當前會話
您需要在第二個 servlet 的請求中檢查您收到的會話 ID。 您可以使用getRequestedSessionId
做到這一點
僅當您的會話在兩次調用之間或在瀏覽器獲取session id
之前您已調用SeveletB
失效時,才會發生這種情況
它實際上取決於 servlet 的順序:
通常,如果您想避免自動創建會話 - 您必須確保在創建會話的代碼之前永遠不會執行使用會話的代碼。
所以好的做法是,如果會話為空,則將用戶從 servlet B 重定向到 servlet A。
正如您所提到的, servletA
調用servletB
, servletA
調用servletB
。
如果如你所提到的什么也沒有發生,此外,您會收到在同一個會話(NOT NULL) servletB
其用於/中創建servletA
。
在 servletA 中,
getSession(true) in servletA means create and return the session if not
present otherwise return the existing session
在servletB中,
getSession(false) in servletB means return the existing session if present
otherwise return null.
由於您肯定已經在servletA
創建了一個會話,您將在servletB
收到非空會話,前提是在兩次調用之間沒有發生任何事情來清除您的會話,例如會話過期。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.