运用Listener步骤
经由过程完成细致接口建立完成类(可完成多个监听器接口)
设置完成类成为监听器,有两种设置体式格局:
直接用@WebListener注解润饰完成类
经由过程web.xml体式格局设置,代码以下:
<listener> <listener-class>com.zrgk.listener.MyListener</lisener-class> </listener>
经常使用Web事宜监听器接口
1. ServletContextListener
该接口用于监听Web运用的启动与封闭
该接口的两个要领:
contextInitialized(ServletContextEvent event); // 启动web运用时挪用 contextDestroyed(ServletContextEvent event); // 封闭web运用时挪用
怎样取得application对象:
ServletContext application = event.getServletContext();
示例:
@WebListener public class MyServetContextListener implements ServletContextListener{ //web运用封闭时挪用该要领 @Override public void contextDestroyed(ServletContextEvent event) { ServletContext application = event.getServletContext(); String userName = application.getInitParameter("userName"); System.out.println("封闭web运用的用户名字为:"+userName); } //web运用启动时挪用该要领 @Override public void contextInitialized(ServletContextEvent event) { ServletContext application = event.getServletContext(); String userName = application.getInitParameter("userName"); System.out.println("启动web运用的用户名字为:"+userName); } }
2. ServletContextAttributeListener
该接口用于监听ServletContext局限(application)内属性的转变。
该接口的两个要领:
attributeAdded(ServletContextAttributeEvent event);//当把一个属性存进application时触发 attributeRemoved(ServletContextAttributeEvent event);//当把一个属性从application删除时触发 attributeReplaced(ServletContextAttributeEvent event);//当替代application内的某个属性值时触发
怎样取得application对象:
ServletContext application = event.getServletContext();
示例:
@WebListener public class MyServletContextAttributeListener implements ServletContextAttributeListener{ //向application局限内增加一个属性时触发 @Override public void attributeAdded(ServletContextAttributeEvent event) { String name = event.getName();//向application局限增加的属性名 Object val = event.getValue(); //向application增加的属性对应的属性值 System.out.println("向application局限内增加了属性名为:"+name+",属性值为:"+val+"的属性"); } //删除属性时触发 @Override public void attributeRemoved(ServletContextAttributeEvent event) { // ... } //替代属性值时触发 @Override public void attributeReplaced(ServletContextAttributeEvent event) { // ... } }
以上就是java listers怎样用的细致内容,更多请关注ki4网别的相干文章!