栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

Java学习笔记之监听器与过滤器

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java学习笔记之监听器与过滤器

监听器:

建立一个类,通过实现ServletContextListener来得到它的功能,即配置服务器:

public void sessionCreated(HttpSessionEvent hse)

 例如:

package com.servlet;

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 OnLinelistenter implements ServletContextListener,HttpSessionListener{
	ServletContext  application;
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		//application被销毁了
		System.out.println("服务关闭");
		
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		//application被创建了
		System.out.println("服务启动");
		 application = sce.getServletContext();
		//项目启动时,人数设置为0
		 application.setAttribute("onLineCount", 0);
	}

	@Override
	public void sessionCreated(HttpSessionEvent hse) {
		// 项目页面被访问
		//获取人数
		Integer count=(Integer) application.getAttribute("onLineCount");
		//人数加1
		//设置人数
		application.setAttribute("onLineCount",++count );
		System.out.println("有人进来,人数:"+count+"");
		
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent hse) {
		// 1.存活时间ttl到期,session被销毁
		//2.手动关闭 req.getSession().invalidate();
		Integer count=(Integer)application.getAttribute("onLineCount");
		//人数减1
		//设置人数
		application.setAttribute("onLineCount", --count);
		System.out.println("有人出去,人数"+count+"");
	}

}
过滤器 Filter 规则: 精准匹配 /a.jsp 扩展名匹配 *.jsp 路径匹配 /manager @WebFilter("/*")//设置过滤规则 public class RoleFilter implements Filter{ List paths=new ArrayList(); //将路径放入集合 { paths.add("/tourists.jsp"); paths.add("/index.jsp"); paths.add("/login.do"); } @Override public void destroy() { // TODO Auto-generated method stub } @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(); boolean f=false; for (String p : paths) { if(p.equals(paths)) { f=true; break; } } if(f) {//如果当前访问的是游客界面 chain.doFilter(req, resp); return; } //登陆之后放入session里面去的isLogin Object isLogin = request.getSession().getAttribute("isLogin"); if(isLogin==null) {//没有登陆 response.sendRedirect("index.jsp"); return; } //让过滤器放行 chain.doFilter(req, resp); } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/829991.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号