How to create and use a JSP session?
In JSP, you can create and use a session with the following code.
- Start a conversation.
<%
// 获取请求对象的会话
HttpSession session = request.getSession();
// 或者创建一个新的会话
HttpSession session = request.getSession(true);
// 或者获取现有的会话, 如果不存在则返回null
HttpSession session = request.getSession(false);
%>
- Set conversation properties:
<%
// 设置会话属性
session.setAttribute("username", "John");
%>
- Retrieve conversation attributes.
<%
// 获取会话属性
String username = (String) session.getAttribute("username");
%>
- Remove conversation properties.
<%
// 删除会话属性
session.removeAttribute("username");
%>
- 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.