How to create and use a JSP session?

In JSP, you can create and use a session with the following code.

  1. Start a conversation.
<%
   // 获取请求对象的会话
   HttpSession session = request.getSession();
   
   // 或者创建一个新的会话
   HttpSession session = request.getSession(true);
   
   // 或者获取现有的会话, 如果不存在则返回null
   HttpSession session = request.getSession(false);
%>
  1. Set conversation properties:
<%
   // 设置会话属性
   session.setAttribute("username", "John");
%>
  1. Retrieve conversation attributes.
<%
   // 获取会话属性
   String username = (String) session.getAttribute("username");
%>
  1. Remove conversation properties.
<%
   // 删除会话属性
   session.removeAttribute("username");
%>
  1. Destroy the conversation.
<%
   // 销毁会话
   session.invalidate();
%>

It is important to note that, before using the session, you must first obtain the session object through request.getSession() method.

bannerAds