gpt4 book ai didi

java - Springboot SessionListener 函数(sessionCreated()、sessionDestroyed())未调用

转载 作者:行者123 更新时间:2023-12-01 16:18:24 24 4
gpt4 key购买 nike

我目前正在开发一个 springboot 项目,我想在创建/销毁 session 时执行某些命令。我创建的类 SessionListener 如下所示。

package cn.mypackage.listener;

import java.util.HashSet;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class SessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent event) {
System.out.println("Session Created ---- ");

HttpSession session = event.getSession();
session.setMaxInactiveInterval(10);
System.out.println("Current Session: " + session.getId());

ServletContext application = session.getServletContext();
HashSet<HttpSession> sessions = (HashSet<HttpSession>) application.getAttribute("sessions");
if (sessions == null) {
sessions = new HashSet<HttpSession>();
application.setAttribute("sessions", sessions);
}
sessions.add(session);
System.out.println("Current available sessions: " + Integer.valueOf(sessions.size()).toString());
}

@Override
public void sessionDestroyed(HttpSessionEvent event) throws ClassCastException {
System.out.println("Session Destroyed ---");

HttpSession session = event.getSession();
System.out.println("deletedSessionId: " + session.getId());
System.out.println(session.getCreationTime());
System.out.println(session.getLastAccessedTime());

ServletContext application = session.getServletContext();
HashSet<HttpSession> sessions = (HashSet<HttpSession>) application.getAttribute("sessions");
sessions.remove(session);
}
}

我把这个SessionListener.java放在我的/src/main/java/cn/mypackage/listener/文件夹中,我的入口文件在/src/main/java/cn/mypackage/.

但是,每当我打开一个新的私有(private)浏览器窗口并尝试访问任何网址时,服务器端都不会输出任何信息,并且这两个函数中的断点都没有用。

最佳答案

事实证明,问题是我尝试访问的所有 @RequestMapping 都没有传递 HttpSession 参数。仅当访问带有 HttpSession 参数的 url 时,才会创建 session (如果之前没有)。

示例:

@Controller
public class APIController {
// this will not generate a session if no session exists, therefore not calling the sessionCreated() function
@RequestMapping("/test1")
public @ResponseBody String test1() {
return "test without session";
}

// this will generate a session if no session exists, therefore calling the sessionCreated() function
@RequestMapping("/test2")
public @ResponseBody String test2(HttpSession session) {
return "test with session";
}
}

关于java - Springboot SessionListener 函数(sessionCreated()、sessionDestroyed())未调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62339940/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com