监听器和过滤器技术
过滤器
- 过滤器是作用在servlet之外的,对HttpservletRequest和HttpServletResponse进行处理
过滤机制包含的接口
- Filter接口
- FilterConfig接口
- FilterChain接口
这些接口都包含在javax.servlet包中
主要使用的接口Filter接口
接口中需要实现三种方法
- void init(FilterConfig filterConfig) 在创建Filter对象的时候进行调用
- void doFilter(HttpServletRequst req, HttpServletResponse resp, FilterChain(chain)) 包含主要的过滤功能
- void destroy(): 销毁过滤器的时候被调用
在doFilter中需要调用chain的doFilter方法,否则就会造成请求的拦截
关于过滤器的文件配置
使用xml进行配置
其中的init-param的作用为flter的初始化值
url-pattern的作用为指定filter对那些请求有效
使用标签来陪配置过滤器
@WebFilter(fileName, value, urlPatterns, servletNames, initParams)
在使用initParams属性的使用需要注意的是,initParams本身就是一个标签属性
inintParams = {@WebInitParams(name="", value="")}
<!-- urlPatterns和xml中配置的作用是一样的, fileName的作用和fileter-name效果是一样的-->
监听器
监听器主要是用来监听web应用的启动和关闭的,通过监听web应用状态的改变,来引起相应的serlvet容器产生事件,做出相应的处理
监听器接口
8个监听器接口, 6个Event类
监听对象的创建与销毁
application, session, request对象创建和销毁所对应的接口分别是ServletContextListener, HttpSessionListener, ServletRequestListener
这三个接口中都只包含两种方法Created(), Destoryed()
监听对象的属性的状态变化
application, session, request对象对应的接口分别是ServletContextAttributeListener, HttpSessionAttributeListener, ServletRequestAttributeListener
这三个接口中都只包含三种方法attributeAdded(), attributeRemoved(),attributeReplace(*)
监听session中的对象
使用的接口为HttpSessionBindingListener和HttpSessionActivationListener
- HttpSessionBindingListener用于监听session中的绑定信息
valueBound():当加入session范围的对象的时候调用
valueUnbound():当移除session范围的对象的时候调用
- HttpSessionBindingListener用于监听session中的绑定信息
关于统计网站登陆人数的小web程序
**其中login.jsp负责进行用于登陆的界面**
**index.jsp负责进行登陆成功之后的页面显示**
**ServletLogin负责登陆之后对进行设置属性**
**ServletExit负责在点击对出登陆之后进行的删除的操作**
**onlindeListener负责响应当session中对象的属性变化**
对于用户队列的修改是发生在监听器的事件中的,在servlet中进行的只是session属性的修改,可以将这些看作是一个标志位的修改
关于HttpSessionBindingEvent类的使用
- getName(): 获得删除,或者添加,覆盖的属性的名字
- getValue(): 获得被删除,添加,覆盖的属性的值
- getSession(): 获得当前对象的session