首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> JSP 程式設計 >> 關於JSP

JSP 取得 Action 傳遞的 Session、清空與判斷實用技巧

     編輯:關於JSP

取得 Session 值的三種方式

假設 Action 中 session.put("sessionid", "sessionValue")。

  1. Struts 標籤:<s:property value="#session.sessionid" />
  2. JSP 內建物件:<%= session.getAttribute("sessionid") %>(session 為隱含物件,比 request.getSession() 更簡潔)
  3. EL 運算式:${sessionScope.sessionid}
    若為 Bean:${sessionScope.bean.property}

判斷 Session 是否存在(避免空指標)

<%
    String id = "", username = "";
    User user = (User) session.getAttribute("docUser");
    if (user != null) {
        id = user.getId();
        username = user.getUsername();
    }
%>

清空 Session

<%
    Lduser lduser = (Lduser) ActionContext.getContext().getSession().get("lduser");
    if (lduser == null) {
        session.setAttribute("lduser", null); // 或 session.removeAttribute("lduser")
        out.println("session已關閉");
    }
%>

注意:session.invalidate() 會銷毀整個 Session;若僅清除某屬性,用 removeAttribute 或設為 null。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved