过滤器
在3.0中使用标注声明一个过滤器:
@WebFilter(filterName = "EncodingFilter",
urlPatterns="/*",
initParams=@WebInitParam(name="charset",value="UTF-8"))
这是一个简单的编码过滤器范例,使用了常用的三个属性,指定过滤器名(filterName),过滤器应用对象(urlPatterns,这里对所有页面都使用),初始化参数(initParams)。
应用实例:应用过滤器进行登录验证
由于过滤器中对象定义的是ServletRequest,而session本身是属于HTTP协议的范畴,那么要想获得session,则必须进行向下转型,将ServletRequest变为HttpServletRequest接口对象,才能通过getSession()方法取得session对象。
监听器
在3.0中使用标注定义一个监听器只需在类前声明@WebListener()即可
对application监听:
1.上下文状态监听:ServletContextListener接口,接口定义的方法:
| void contextInitialized(ServletContextEvent sce) | 容器启动时触发 |
| void conetxtDestroyed(ServletContextEvent see) | 容器销毁时触发 |
一旦触发ServletContextListener接口中定义的事件后,可以通过ServletContextEvent进行事件的处理,事件定义的方法:
| ServletContext getServletContext() | 取得ServletContext对象 |
2.上下文属性监听:ServletContextAttributeListener接口,接口定义的方法:
| void attributeAdded(ServletContextAttributeEvent event) | 增加属性时触发 |
| void
attributeRemoved(ServletContextAttributeEvent event) | 删除属性时触发 |
| void
attributeReplaced(ServletContextAttributeEvent event) | 替换属性时触发 |
一旦触发ServletContextAttributeListener接口中定义的事件后,可以通过ServletContextAttributeEvent进行事件的处理,事件定义的方法:
| String getName() | 取得设置的属性名称 |
| Object getValue() | 取得设置的属性内容 |
另外还可以对其他对象监听,情况和对application类似,方法大同小异,具体方法可以从文档接口方法中查看:
Session 监听接口:session状态监听(HttpSessionListener),session属性监听(HttpSessionAttributeListener和HttpSessionBindingListener)
Request 监听接口:request状态监听(HttpRequestListener),request属性监听(ServletRequestAttributeListener)
应用实例:在线人员统计
需要使用如下3个接口:
ServletContextListener接口:在上下文初始化时设置一个空的集合到applicaton中。
HttpSessionAttributeListener接口:用户增加session属性时,表示新用户登录,从session中取出此登录名,之后将此用户保存在列表中。
HttpSessionListener接口:当用户注销(手工注销、会话超时)时会将此用户从列表中删除