How to set and read session in Java?
In Java, you can use the javax.servlet.http.HttpSession class to set and retrieve session attributes. Here are some common examples of operations:
Set Session value:
// 获取当前请求的HttpSession对象
HttpSession session = request.getSession();
// 设置Session值
session.setAttribute("key", "value");
Get the Session value:
// 获取当前请求的HttpSession对象
HttpSession session = request.getSession();
// 读取Session值
String value = (String) session.getAttribute("key");
Caution: When setting and retrieving session values, the parameter types of the setAttribute() and getAttribute() methods need to match the actual data types. Mismatched types could result in exceptions or incorrect outcomes.