在JSP中,可以使用以下代碼創建和使用會話(Session):
<%
// 獲取請求對象的會話
HttpSession session = request.getSession();
// 或者創建一個新的會話
HttpSession session = request.getSession(true);
// 或者獲取現有的會話, 如果不存在則返回null
HttpSession session = request.getSession(false);
%>
<%
// 設置會話屬性
session.setAttribute("username", "John");
%>
<%
// 獲取會話屬性
String username = (String) session.getAttribute("username");
%>
<%
// 刪除會話屬性
session.removeAttribute("username");
%>
<%
// 銷毀會話
session.invalidate();
%>
需要注意的是,在使用會話之前,必須先通過request.getSession()方法來獲取會話對象。