我目前在springboot项目上工作,我想在创建/销毁会话时执行某些命令。我创建的类如下所示。
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
放在我的SessionListener.java
文件夹中,而我的入口文件在/src/main/java/cn/mypackage/listener/
中。但是,每当我打开一个新的专用浏览器窗口并尝试访问任何URL时,服务器端都不会输出任何信息,这两个函数中的断点都是无用的。
最佳答案
原来的问题是我尝试访问的所有@RequestMapping
都没有传递HttpSession
参数。仅当使用HttpSession
参数访问URL时,才会创建会话(如果之前没有)。
例:
@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";
}
}