本文源码:GitHub·点这里 || GitEE·点这里

一、Listener监听器

1、概念简介

JavaWeb三大组件:Servlet,Listener,Filter。监听器就是指在应用程序中监听相关对象状态变化的组件。

2、事件源对象

指被监听对象。

  • ServletContext

ServletContextListener生命周期监听,它有两个方法,出生时调用contextInitialized(),销毁时调用contextDestroyed();

ServletContextAttributeListener属性监听,它有三个方法,添加属性attributeAdded(),替换属性attributeReplaced(),移除属性时attributeRemoved()

  • HttpSession

HttpSessionListener生命周期监听:它有两个方法,出生时调用sessionCreated(),销毁时调用sessionDestroyed()

HttpSessioniAttributeListener属性监听:它有三个方法,添加属性attributeAdded(),替换属性attributeReplaced(),移除属性attributeRemoved()

  • ServletRequest

ServletRequestListener生命周期监听:它有两个方法,出生时调用requestInitialized(),销毁时调用requestDestroyed()

ServletRequestAttributeListener属性监听:它有三个方法,添加属性attributeAdded(),替换属性attributeReplaced(),移除属性attributeRemoved()

3、编码案例

  • 相关监听器

TheContextListener

public class TheContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("初始化:TheContextListener");
ServletContext servletContext = servletContextEvent.getServletContext() ;
servletContext.setAttribute("author","cicada");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("销毁:TheContextListener");
}
}

TheRequestListener

public class TheRequestListener implements ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
System.out.println("初始化:TheRequestListener");
}
@Override
public void requestInitialized(ServletRequestEvent servletRequestEvent) {
System.out.println("销毁:TheRequestListener");
}
}

TheSessionListener

public class TheSessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
System.out.println("初始化:TheSessionListener");
}
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
System.out.println("销毁:TheSessionListener");
}
}

RequestAttributeListener

public class RequestAttributeListener implements ServletRequestAttributeListener {
@Override
public void attributeAdded(ServletRequestAttributeEvent evt) {
System.out.println("Request添加属性:"+evt.getName()+";"+evt.getValue());
}
@Override
public void attributeRemoved(ServletRequestAttributeEvent evt) {
System.out.println("Request移除属性:"+evt.getName()+";"+evt.getValue());
}
@Override
public void attributeReplaced(ServletRequestAttributeEvent evt) {
System.out.println("Request替换属性:"+evt.getName()+";"+evt.getValue());
}
}
  • web.xml配置文件
<!-- 监听器相关配置 -->
<listener>
<listener-class>com.node05.servlet.listener.TheContextListener</listener-class>
</listener>
<listener>
<listener-class>com.node05.servlet.listener.TheSessionListener</listener-class>
</listener>
<listener>
<listener-class>com.node05.servlet.listener.TheRequestListener</listener-class>
</listener>
<listener>
<listener-class>com.node05.servlet.listener.RequestAttributeListener</listener-class>
</listener>
<session-config>
<!-- 设置session失效时间为1分钟 -->
<session-timeout>1</session-timeout>
</session-config>
  • 测试接口
public class ListenerServletImpl extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
// 1、获取TheContextListener初始化数据
ServletContext servletContext = this.getServletContext() ;
String author = String.valueOf(servletContext.getAttribute("author")) ;
System.out.println("TheContextListener Author:"+author);
// 2、Request属性设置
request.setAttribute("mood","smile");
request.setAttribute("mood","agitated");
// 3、Session创建,1分钟失效,调用销毁
HttpSession session = request.getSession(true) ;
session.setAttribute("casually","casually");
response.getWriter().print("Hello:Listener");
}
}

二、Filter过滤器

1、过滤器简介

客户端请求Servlet时,先执行相关Filter,如果Filter通过,则继承执行请求的Servlet;如果Filter不通过,则不会执行用户请求的Servlet。过滤器可以动态地拦截请求和响应。

2、Filter接口

Filter接口定义了三个核心方法。

  • init()

应用程序启动时,服务器实例化Filter对象,并调用其init方法,读取web.xml配置,完成对象的初始化加载。

  • doFilter()

实际的过滤操作,请求达到服务器时,Servlet容器将先调用过滤器的doFilter方法。

  • destroy()

容器在销毁过滤器前调用该方法,释放过滤器占用的资源。

3、编码案例

  • 编写过滤器
public class ThePrintLogFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String myName = filterConfig.getInitParameter("myName") ;
System.out.println("myName:"+myName);
}
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)servletRequest ;
HttpServletResponse response = (HttpServletResponse)servletResponse ;
String name = request.getParameter("name") ;
if (!name.equals("cicada")){
response.getWriter().print("User Error !");
return ;
}
chain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
System.out.println("ThePrintLogFilter destroy()");
}
}
  • web.xml配置文件
<!-- 过滤器相关配置 -->
<filter>
<filter-name>thePrintLogFilter</filter-name>
<filter-class>com.node05.servlet.filter.ThePrintLogFilter</filter-class>
<init-param>
<param-name>myName</param-name>
<param-value>cicada</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>thePrintLogFilter</filter-name>
<url-pattern>/filterServletImpl</url-pattern>
</filter-mapping>
  • 测试接口
public class FilterServletImpl extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
response.getWriter().print("Hello:Filter");
}
}

三、Interceptor拦截器

Spring框架中的拦截器Interceptor类似于Servlet中的过滤器Filter,主要用于拦截用户请求并作相应的处理。例如通过拦截器可以进行权限验证、记录请求信息的日志、判断用户是否登录等。请求转发不执行拦截、过滤;重定向执行拦截和过滤。

四、源代码地址

GitHub·地址
https://github.com/cicadasmile/java-base-parent
GitEE·地址
https://gitee.com/cicadasmile/java-base-parent

JavaEE基础(05):过滤器、监听器、拦截器,应用详解的更多相关文章

  1. JavaWeb过滤器.监听器.拦截器-原理&区别-个人总结

    对比项 拦截器 过滤器 机制 反射机制 函数回调 是否依赖servlet容器 是 否 请求处理 只能对action请求起作用 几乎所有的请求起作用 对action处理 可以访问action上下文.值栈 ...

  2. JavaWeb过滤器.监听器.拦截器-原理&区别(转)

    1.拦截器是基于java的反射机制的,而过滤器是基于函数回调 2.过滤器依赖与servlet容器,而拦截器不依赖与servlet容器 3.拦截器只能对action请求起作用,而过滤器则可以对几乎所有的 ...

  3. AOP,过滤器,监听器,拦截器【转载】

    面向切面编程(AOP是Aspect Oriented Program的首字母缩写) ,我们知道,面向对象的特点是继承.多态和封装.而封装就要求将功能分散到不同的对象中去,这在软件设计中往往称为职责分配 ...

  4. JavaWeb过滤器.监听器.拦截器-?原理&区别

    过滤器可以简单理解为“取你所想取”,忽视掉那些你不想要的东西:拦截器可以简单理解为“拒你所想拒”,关心你想要拒绝掉哪些东西,比如一个BBS论坛上拦截掉敏感词汇. 1.拦截器是基于java的反射机制,过 ...

  5. 过滤器 & 监听器 & 拦截器

    过滤器: https://blog.csdn.net/MissEel/article/details/79351231 https://blog.csdn.net/qq_32363305/articl ...

  6. springboot拦截器HandlerInterceptor详解

    Web开发中,我们除了使用 Filter 来过滤请web求外,还可以使用Spring提供的HandlerInterceptor(拦截器). HandlerInterceptor 的功能跟过滤器类似,但 ...

  7. 拦截器 应用详解--SpringMVC

    在实际项目中,拦截器的使用是非常普遍的,例如在购物网站中通过拦截器可以拦截未登录的用户,禁止其购买商品,或者使用它来验证已登录用户是否有相应的操作权限等,Spring MVC提供了拦截器功能,通过配置 ...

  8. mybatis Interceptor拦截器代码详解

    mybatis官方定义:MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis ...

  9. Flume 拦截器(interceptor)详解

    flume 拦截器(interceptor)1.flume拦截器介绍拦截器是简单的插件式组件,设置在source和channel之间.source接收到的事件event,在写入channel之前,拦截 ...

  10. Spring 注解拦截器使用详解

    Spring mvc拦截器 平时用到的拦截器通常都是xml的配置方式.今天就特地研究了一下注解方式的拦截器. 配置Spring环境这里就不做详细介绍.本文主要介绍在Spring下,基于注解方式的拦截器 ...

随机推荐

  1. javascript jquery 修改指定标签中的内容

    javascript jquery 修改指定标签中的内容 $("#test1").text("Hello world!"); document.getEleme ...

  2. thinking in JAVA 编译记录

    编辑/编译<thinking in JAVA>源代码 一.下载源代码 首先,我阅读的是<thinking in JAVA>第四版,因此按照书中提供的链接找到了mindview主 ...

  3. Flex调用本地文件分析

    最近在用Flex做一个相册的功能,因为图片数据很多,所以想调用本地文件的方式做. 但是B/S的缘故,很多安全上的限制给我造成了不小的麻烦,把我这个小菜鸟弄的晕头转向. 第一,刚开始,查了很多资料发现都 ...

  4. 设计模式之美学习(九):业务开发常用的基于贫血模型的MVC架构违背OOP吗?

    我们都知道,很多业务系统都是基于 MVC 三层架构来开发的.实际上,更确切点讲,这是一种基于贫血模型的 MVC 三层架构开发模式. 虽然这种开发模式已经成为标准的 Web 项目的开发模式,但它却违反了 ...

  5. Hadoop运行模式

    Hadoop运行模式 (1)本地模式(默认模式): 不需要启用单独进程,直接可以运行,测试和开发时使用. 即在一台机器上进行操作,仅为单机版. 本地运行Hadoop官方MapReduce案例 操作命令 ...

  6. odoo12 修行基础篇之 添加明细字段 (二)

    前一篇介绍了如何在视图和表单中添加字段.本节内容,我们讨论下如何在明细中加字段. 我想在销售页面明细中增加税额字段,这在表sale.order.line中已经存在,在此仅用来演示. odoo的明细一般 ...

  7. 2019-10-9:渗透测试,基础学习,php文件上传,mysql基础

    header("Content-Type:text/html;charst="utf-8")设置头部信息,解决编码问题setcookie("loginStrin ...

  8. Centos 7.x 内核升级

    作者信息 邮箱:sijiayong000@163.com Q Q:601566386 Centos 7.x 内核升级 注意:这篇文章只在 CentOS 7.× 系列版本上验证过,其他 CentOS 版 ...

  9. 【SSL1457】翻币问题

    题面: \[\Large\text{翻币问题}\] \[Time~Limit:1000MS~~Memory~Limit:65536K\] Description 有N个硬币(6<=N<=2 ...

  10. 利用scatter()绘制颜色映射的二次方曲线

    程序如下: import matplotlib.pyplot as plt x_value = list(range(1, 1001)) y_value = [x**2 for x in x_valu ...