用户点击退出后的处理程序,这里的处理是删除会话session并重定向到登陆界面
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DistoryServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //清除session并重定向到登陆界面 request.getSession().invalidate(); response.sendRedirect("login.html"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }监听器处理程序,用一个变量来统计在线人数,每建立一个会话我们就让变量增加1,每销毁一个会话我们就让变量减少1
package listener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class LoginListener implements HttpSessionListener { int uerNumber = 0; //用来统计在线人数的变量 public void sessionCreated(HttpSessionEvent arg0) { uerNumber++; //将变量设为应用上下文的属性,便于在整个项目都可以访问到在线人数 arg0.getSession().getServletContext().setAttribute("uerNumber", uerNumber); System.out.println("当前在线用户:"+uerNumber); } public void sessionDestroyed(HttpSessionEvent arg0) { uerNumber--; //将变量设为应用上下文的属性,便于在整个项目都可以访问到在线人数 arg0.getSession().getServletContext().setAttribute("uerNumber", uerNumber); System.out.println("当前在线用户:"+uerNumber); } } 结果如图:以上就是Servlet中的
过滤器(Filter)和监听器(Listener)