簡體   English   中英

在servlet和jsp中檢查會話

[英]checking session in servlet and jsp

在我的Web應用程序中,我需要檢查會話是否已存在。

我想在我的servlet和jsp中檢查這個。

有沒有辦法檢查這個。

謝謝

您可以使用帶有create=false HttpServletRequest#getSession(boolean create)對其進行測試。 如果尚未創建,它將返回null。

HttpSession session = request.getSession(false);
if (session == null) {
    // Session is not created.
} else {
    // Session is already created.
}

如果你真的想要創建會話,如果它不存在,那么只需抓住它並使用HttpSession#isNew()測試新鮮度:

HttpSession session = request.getSession();
if (session.isNew()) {
    // Session is freshly created during this request.
} else {
    // Session was already created during a previous request.
}

這就是你如何在Servlet中做到這一點。 在JSP中,您只能在JSTL和EL的幫助下測試新鮮度。 您可以通過PageContext#getSession()獲取會話,然后在其上調用isNew()

<c:if test="${pageContext.session.new}">
    <p>Session is freshly created during this request.</p>
</c:if>

要么

<p>Session is ${pageContext.session.new ? 'freshly' : 'already'} created.</p>

一種方法是在jsp中設置會話ID,然后在另一個jsp或servlet中檢查相同的會話ID,以檢查它是否存活。

HttpSession session = req.getSession();
        session.getId();

暫無
暫無

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

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