How is session existence detected in Java?

In Java, you can use the getAttribute() method of the HttpSession object to check if a session exists. If the getAttribute() method returns null, it means the session does not exist. Here is an example code:

// 获取当前请求的session对象
HttpSession session = request.getSession(false);

// 判断session是否存在
if (session != null && session.getAttribute("username") != null) {
    // session存在
    String username = (String) session.getAttribute("username");
    System.out.println("当前用户是:" + username);
} else {
    // session不存在
    System.out.println("session不存在");
}

In the sample code, the request.getSession(false) method is first used to retrieve the current request’s session object, with the parameter set to false indicating that a new session should not be created if one does not exist. The getAttribute() method is then used to retrieve data stored in the session, such as the username. If the getAttribute() method returns null, it means the session does not exist.

bannerAds