HttpSessionListener主类:
package com.httpSessionListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class OnlineNum implements HttpSessionListener{
//静态变量累计count,这个过程中每一个用户将new一个OnlineNum实例出来
private static int count;
public static int getCount() {
return count;
}
//session创建时将创建对象并调用此方法
public void sessionCreated(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("增加了");
count++;
}
//浏览器关闭或手动关闭session时将调用该方法
public void sessionDestroyed(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
count--;
}
}
2,创建session的类
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getSession().setAttribute("user", "user");
System.out.println(request.getSession().getAttribute("user"));
request.getRequestDispatcher("index.jsp").forward(request, response);
//response.sendRedirect(request.getContextPath()+"/index.jsp");
}