- 过滤器 Filter
1.1 概念
在浏览器和目标资源之间进行过滤的中间组件。 请求到达目标资源之前进行过滤。 响应到达浏览器之前进行过滤。 |
1.2 定义过滤器的步骤
1. 写一个java类,实现Filter接口
public class FirstFilter implements Filter { |
2. 配置哪些目标资源需要经过过滤器 (两种方式)
1. web.xml进行配置
<filter> |
2. 在类上使用注解方式进行配置
@WebFilter(filterName = "EncodingFilter",urlPatterns = "/*") public class FirstFilter implements Filter { } |
1.3 执行原理 (生命周期)
1. 服务器启动时,加载web.xml以及扫描@WebFilter注解, 创建filter对象,调用init()进行初始化(执行1次) 2. 请求过滤器过滤的目标资源,调用doFilter()方法 (执行多次)。 如果遇到filterChain.doFilter(request,response);则进行放行, 进入下一个过滤器或目标资源。 3.服务器停止时,调用destroy()销毁方法(执行1次) |
1.4 过滤器链
过滤器链:由多个过滤器组成。 执行顺序:web.xml配置方式,与<filter-mapping>配置顺序有关,在前面的先执行。 @WebFilter注解方式,顺序按照过滤器名称字母字典顺序一次执行. 如AFilter比BFilter先执行。 核心代码:filterChain.doFilter(request,response);放行进入下一个过滤器或目标资源。 |
1.5 典型应用
1. 设置统一字符编码 2. 登录验证 3. 敏感字符的替换 |
- 监听器 Listener
1. 概念
监听域对象的创建和销毁 监听域对象的属性操作。(增加、修改、删除) |
2. 分类
监听域对象的创建和销毁 ServletRequestListener HttpSessionListener ServletContextListener 监听域对象的属性操作 ServletRequestAttributeListener HttpSessionAttributeListener ServletContextAttributeListener |
3. 典型应用
1. 统计在线人数 |
4. 统计在线人数实现步骤
1. 创建一个Listener监听器的类,监听session创建和销毁。实现HttpSessionListener
/** * 监听session的创建 */ @WebListener public class OnlineNumListener implements HttpSessionListener{ public OnlineNumListener() { } /** * 监听session对象创建调用,在线人数+1 */ @Override public void sessionCreated(HttpSessionEvent se) { ServletContext application=se.getSession().getServletContext(); if(application.getAttribute("count")!=null){ int count =(int)application.getAttribute("count"); application.setAttribute("count",count+1); }else{ application.setAttribute("count",1); } } /** * 监听session销毁调用,在线人数-1 */ @Override public void sessionDestroyed(HttpSessionEvent se) { ServletContext application=se.getSession().getServletContext(); int count =(int)application.getAttribute("count"); application.setAttribute("count",count-1); } } |
2. 编写jsp页面展示在线人数
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <body> <h2>在线人数:${count}</h2> <a href="exitServlet">退出</a> </body> </html> |
3. 退出
@WebServlet(name = "ExitServlet", value = "/exitServlet") public class ExitServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session=request.getSession(); //销毁session session.invalidate(); } } |