众所周知,sessionCreated方法是用来监听HttpSession对象创建的,每当有新的HttpSession对象创建时,该方法自动被执行。
楼主今天想在sessionCreated监听项目当前共创建了几个HttpSession对象。
@WebListener
public class MyHttpSessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
try {
Connection connection = JDBCUtils.getConnection();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String d = dateFormat.format(date);
String insertSql = "insert into session(date)values(?)";
PreparedStatement insertPrepareStatement = connection.prepareStatement(insertSql);
insertPrepareStatement.setString(1,d);
insertPrepareStatement.executeUpdate();
String selectSql = "select count(*) from session where date = ?";
PreparedStatement selectPreparedStatement = connection.prepareStatement(selectSql);
selectPreparedStatement.setString(1,d);
ResultSet resultSet = selectPreparedStatement.executeQuery();
int count=0;
while (resultSet.next()) {
count = resultSet.getInt(1);
}
System.out.println("当前项目已创建"+count+"个HttpSession");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
HttpSessionListener.super.sessionDestroyed(se);
}
}
@WebServlet("/servlet")
public class Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getSession();
}
}
但当我启动项目时,直接显示调用了三次sessionCreated方法。
还没有访问Servlet调用getSession方法就出现这种情况,目前原因并不清楚。
但是应该是tomcat启动访问首页的index.jsp时触发的。
<%@ page session="false"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
首页(session禁止)
</body>
</html>
在index.jsp中加入<%@ page session="false"%> 禁用掉当前静态页面的会话功能就ok了。
这样保证只在getSession创建HttpSession时,才调用sessionCreated方法并执行相关代码。