ServletContextListener 上下文监听器
HttpSessionListener 会话监听器
ServletRequestListener 请求监听器一定要在监听器的类上加上 WebListener ,否则该监听器不会被启用
监听器的作用: 能够针对创建和销毁定义不同的行为
package com.zking.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
@WebListener //配置监听器
public class OnLineListener implements ServletContextListener,HttpSessionListener{
ServletContext application;
@Override
public void contextInitialized(ServletContextEvent sce) {
//application被创建了
System.out.println("服务被启动了");
//将程序的上下文赋值给了全局对象
application = sce.getServletContext();
//项目启动的时候 把人数设置为0
application.setAttribute("onLineCount",0);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
//application被销毁了
System.out.println("服务被销毁了");
}
@Override
public void sessionCreated(HttpSessionEvent arg0) {
//只要该项目的页面被访问了
//获取application中存放的人数
Integer count=(Integer)application.getAttribute("onLineCount");
//设置人数
application.setAttribute("onLineCount",++count);
System.out.println("有人进来了,人数:"+count);
}
@Override
public void sessionDestroyed(HttpSessionEvent arg0) {
//1.存活时间 ttl 到期了
//2.手动销毁 req.getSession.invalidate():
//获取application中存放的人数
Integer count=(Integer)application.getAttribute("onLineCount");
//设置人数
application.setAttribute("onLineCount",--count);
System.out.println("有人出去了,人数:"+count);
}
}
二、过滤器 Filter
1、过滤器实际上就是对Web资源进行拦截,做一些处理后再交给下一个过滤器或Servlet处理
2、设置过滤的规则
精准匹配 /a.jsp
扩展名匹配 *.jsp
路径匹配 /manager @WebFilter("/*") //设置过滤的规则 public class RoleFilter implements Filter{ //放我不需要过滤的路径 List
paths=new ArrayList (); //将路径放到当前的列表中 { paths.add("/index.jsp"); paths.add("/tourists.jsp"); paths.add("/login.do"); paths.add("/exit.do"); } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { //过滤器的所有操作全部在这里完成 HttpServletRequest request=(HttpServletRequest)req; HttpServletResponse response=(HttpServletResponse)resp; //获取当前请求的路径 String path=request.getServletPath(); //判断你当前访问的路径是否需要过滤 /index.jsp boolean f=false; for (String p : paths) { if(p.equals(path)) { f=true; break; } } if(f) {//当你的访问路径在列表中 我是不需要过滤的 //让过滤器放行 chain.doFilter(req, resp); return;//终止代码运 } //isLogin是在登陆之后被放到session里面去 Object isLogin = request.getSession().getAttribute("isLogin"); if(isLogin==null) {//没有登陆 //回首页 response.sendRedirect("index.jsp"); return; } //让过滤器放行 chain.doFilter(req, resp); } @Override public void destroy() { // TODO Auto-generated method stub } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }



