WEB中的监听器
WEB 中的 Listener 和 Filter 是属于 Servlet 规范中的高级的技术.
WEB中的监听器共有三类八种(监听三个域对象)
* 事件源:Servlet 中的三个域对象.ServletContext,HttpSession,ServletRequest.
* 监听器:自定义类实现8个接口.
* 事件源和监听器的绑定:配置.
监听器的分类
三类八种:
* 一类:监听三个域对象的创建和销毁的监听器
* ServletContextListener
* HttpSessionListener
* ServletRequestListener
* 二类:监听三个域对象的属性变更的监听器(属性添加,移除,替换)
* ServletContextAttributeListener
* HttpSessionAttributeListener
* ServletRequestAttributeListener
* 三类:监听HttpSession中的 JavaBean 的状态改变(绑定,解除绑定,钝化,活化)
* HttpSessionBindingListener
* HttpSessionActivationListener
WEB中的监听器的使用
编写一个类实现监听器的接口;
通过配置文件配置监听器;
一类:监听三个域对象的创建和销毁的监听器
ServletContextListener:监听ServletContext对象的创建和销毁
方法
void contextDestroyed(ServletContextEvent sce)
Notification that the servlet context is about to be shut down.
void contextInitialized(ServletContextEvent sce)
Notification that the web application initialization process is starting.
ServletContext 对象的创建和销毁
创建:服务器启动的时候,服务器为每个WEB应用创建一个属于该web项目的对象ServletContext.
销毁:服务器关闭或者项目从服务器中移除的时候.
应用
public class MyServletContextListener implements ServletContextListener{ @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("ServletContext对象被创建了..."); } @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("ServletContext对象被销毁了..."); } }
配置: <!-- 配置监听器 --> <listener> <listener-class>com.boomoom.weblistener.MyServletContextListener</listener-class> </listener>
企业中的应用
1、加载框架的配置文件: Spring框架 ContextLoaderListener
2、定时任务调度:java.util.Timer,java.util.TimerTask
Timer的方法
void schedule(TimerTask task, Date firstTime, long period)
安排指定的任务在指定的时间开始进行重复的固定延迟执行。
void schedule(TimerTask task, long delay)
安排在指定延迟后执行指定的任务。
void scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
安排指定的任务在指定的时间开始进行重复的固定速率执行。
void scheduleAtFixedRate(TimerTask task, long delay, long period)
安排指定的任务在指定的延迟后开始进行重复的固定速率执行。
ServletContextListener执行任务调度
public class MyServletContextListener implements ServletContextListener{ @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("ServletContext对象被创建了..."); Timer timer = new Timer(); /*Calendar calendar = Calendar.getInstance(); calendar.set(2016,3,11,10,18,00); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { System.out.println("发送邮件:"); } }, calendar.getTime(), 5000);*/ timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { System.out.println("发送邮件:"); } }, 10000, 2000); } @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("ServletContext对象被销毁了..."); } }
HttpSessionListener:监听HttpSession的创建和销毁的监听器
方法
void sessionCreated(HttpSessionEvent se)
Notification that a session was created.
void sessionDestroyed(HttpSessionEvent se)
Notification that a session is about to be invalidated.
HttpSession何时创建和销毁
* 创建:服务器端第一次调用getSession();
* 销毁:
* 非正常关闭服务器(正常关闭session会序列化):
* session过期了默认30分钟.
* 手动调用session.invalidate();
HttpSession的问题
* 访问Servlet会不会创建Session : 不会
* 访问JSP会不会创建Session :会. (Session作为JSP的内置对象,调用了getSession)
* 访问html会不会创建Session :不会
应用
public class MyHttpSessionListener implements HttpSessionListener{ @Override public void sessionCreated(HttpSessionEvent se) { System.out.println("HttpSession被创建了..."); } @Override public void sessionDestroyed(HttpSessionEvent se) { System.out.println("HttpSession被销毁了..."); } } 配置: <listener> <listener-class>com.cnblogs.weblistener.MyHttpSessionListener</listener-class> </listener>
企业中的应用:统计在线人数
public class SessionLinstener implements HttpSessionLinstener { public void sessionCreated(HttpSessionEvent se) { ServletContext sc = se.getSession().getServletContext(); Integer num = (Integer) sc.getAttribute("peopleOnline"); if (null == num) { sc.setAttribute("peopleOnline",1); } else { num++; sc.setAttribute("peopleOnline",num); } } public void sessionCreated(HttpSessionEvent se) { try { ServletContext sc = se.getSession().getServletContext(); Integer num = (Integer) sc.getAttribute("peopleOnline"); num--; sc.setAttribute("peopleOnline",num); } catch (Exception e) { // TODO: handle exception } } }
ServletRequestListener:监听ServletRequest对象的创建和销毁的监听器
方法
void requestDestroyed(ServletRequestEvent sre)
The request is about to go out of scope of the web application.
void requestInitialized(ServletRequestEvent sre)
The request is about to come into scope of the web application.
request对象何时创建和销毁
* 创建:客户端向服务器发送一次请求,服务器就会创建request对象.
* 销毁:服务器对这次请求作出响应后就会销毁request对象.
request的问题
访问一个Servlet会不会创建request对象:会
访问一个JSP会不会创建request对象:会
访问一个HTML会不会创建request对象:会
应用
public class MyServletRequestListener implements ServletRequestListener{ @Override public void requestDestroyed(ServletRequestEvent sre) { System.out.println("ServletRequest被销毁了..."); } @Override public void requestInitialized(ServletRequestEvent sre) { System.out.println("ServletRequest被创建了..."); } } 配置: <listener> <listener-class>com.cnblogs.weblistener.MyServletRequestListener</listener-class> </listener>
企业中监听器的应用
在线人数,在线用户数,访问量,及数据持久化
JavaWeb-Servlet技术的监听器-解析与实例-网站在线用户信息与网页点击量
二类:监听三个域对象的属性变更的监听器:(属性添加,移除,替换)
ServletContextAttributeListener:监听ServletContext对象的属性变更
Method Summary
void attributeAdded(ServletContextAttributeEvent scab)
Notification that a new attribute was added to the servlet context.
void attributeRemoved(ServletContextAttributeEvent scab)
Notification that an existing attribute has been removed from the servlet context.
void attributeReplaced(ServletContextAttributeEvent scab)
Notification that an attribute on the servlet context has been replaced.
HttpSessionAttributeListener:监听HttpSession中的属性变更
Method Summary
void attributeAdded(HttpSessionBindingEvent se)
Notification that an attribute has been added to a session.
void attributeRemoved(HttpSessionBindingEvent se)
Notification that an attribute has been removed from a session.
void attributeReplaced(HttpSessionBindingEvent se)
Notification that an attribute has been replaced in a session.
ServletRequestAttributeListener:监听ServletRequest对象的属性变更
Method Summary
void attributeAdded(ServletRequestAttributeEvent srae)
Notification that a new attribute was added to the servlet request.
void attributeRemoved(ServletRequestAttributeEvent srae)
Notification that an existing attribute has been removed from the servlet request.
void attributeReplaced(ServletRequestAttributeEvent srae)
Notification that an attribute was replaced on the servlet request.
三类:监听HttpSession中的JavaBean的对象的状态改变的监听器
第三类监听器很特殊,不需要进行配置的.作用在JavaBean上的监听器.JavaBean可以自己感知到在Session中的状态.
HttpSessionBindingListener:监听HttpSession中的JavaBean的绑定和解除绑定
Method Summary
void valueBound(HttpSessionBindingEvent event)
Notifies the object that it is being bound to a session and identifies the session.
void valueUnbound(HttpSessionBindingEvent event)
Notifies the object that it is being unbound from a session and identifies the session.
HttpSessionActivationListener:监听HttpSession中的JavaBean的钝化和活化
Method Summary
void sessionDidActivate(HttpSessionEvent se) 活化(反序列化)
Notification that the session has just been activated.
void sessionWillPassivate(HttpSessionEvent se) 钝化(序列化到硬盘)
Notification that the session is about to be passivated.
优化Session:
通过配置<Context>标签配置定时session序列化.
在tomcat/conf/context.xml中配置<Context>:
在tomcat中所有的虚拟主机和虚拟路径都会按照这个配置执行.
在tomcat/conf/Catalina/localhost/context.xml配置<Context>:
在tomcat中的localhost虚拟主机中的所有虚拟路径按照这个配置执行.
在当前的工程下的META-INF/context.xml配置<Context>:
当前这个工程按照配置执行.
当前的工程下的META-INF/context.xml的代码: <?xml version="1.0" encoding="UTF-8"?> <Context> <!-- maxIdleSwap:1 1分钟session会自动序列化到硬盘. directory:cnblogs 序列化后存放的位置.( tomcat/conf/Catalina/localhost/工程名/cnblogs) --> <Manager className="org.apache.catalina.session.PersistentManager" maxIdleSwap="1"> <Store className="org.apache.catalina.session.FileStore" directory="cnblogs"/> </Manager> </Context>
Filter过滤器
过滤器实现自动登录
Cookie技术
利用Cookie记住用户的用户名和密码,设置号有效时间,用户访问页面的时候带入.
Filter:过滤器的概述
过滤器Filter:可以过滤从客户端向服务器发送的请求.
主要方法
void destroy()
void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
void init(FilterConfig filterConfig)
使用过滤器
* 编写一个类实现Filter接口;
* 配置过滤器;
过滤器的生命周期
过滤器的创建和销毁:
* 创建:服务器启动的时候。
* 销毁:服务器关闭的时候。
(1) 加载和实例化 Web 容器启动时,即会根据 web.xml 中声明的 filter 顺序依次实例化这些 filter。 (2) 初始化 Web 容器调用 init(FilterConfig) 来初始化过滤器。容器在调用该方法时,向过滤器传递 FilterConfig 对象,FilterConfig 的用法和 ServletConfig 类似。利用 FilterConfig 对象可以得到 ServletContext 对象,以及在 web.xml 中配置的过滤器的初始化参数。在这个方法中,可以抛出 ServletException 异常,通知容器该过滤器不能正常工作。此时的 Web 容器启动失败,整个应用程序不能够被访问。实例化和初始化的操作只会在容器启动时执行,而且只会执行一次。 (3) doFilter doFilter 方法类似于 Servlet 接口的 service 方法。当客户端请求目标资源的时候,容器会筛选出符合 filter-mapping 中的 url-pattern 的 filter,并按照声明 filter-mapping 的顺序依次调用这些 filter 的 doFilter 方法。在这个链式调用过程中,可以调用 chain.doFilter(ServletRequest, ServletResponse) 将请求传给下一个过滤器(或目标资源),也可以直接向客户端返回响应信息,或者利用 RequestDispatcher 的 forward 和 include 方法,以及 HttpServletResponse 的 sendRedirect 方法将请求转向到其它资源。需要注意的是,这个方法的请求和响应参数的类型是 ServletRequest 和 ServletResponse,也就是说,过滤器的使用并不依赖于具体的协议。 (4) 销毁 Web 容器调用 destroy 方法指示过滤器的生命周期结束。在这个方法中,可以释放过滤器使用的资源。