Listener是Servlet规范的另一个高等特性,它用于监听java web程序的事宜,例如创建、修正、删除session,request,context等,并触发相应的处理事宜,这个处理事宜是由web容器回掉的。

学过安卓开拓的同学一定很熟习view.setonClickLister();这样的对安卓控件的监听。
java web也是这样的 ,根据不同的listner 和不同的event,可以完成相应的处理事宜。

二、Listerner的分类

jsp设计一个监听器web监听器 JavaScript

Listerner分为八种,前三种是用于监听工具的创建和销毁,中间三种用于监听工具属性的变革,后两种用于监听Session内工具。

httpSessionListner: 监听session的创建与销毁,用于网络在线用户信息。
servletContextListener:监听context的创建与销毁,context代表当前web运用,该listener可用于启动时获取web.xml的初始化参数。
servletRequestListener: 监听request 的创建与销毁。
httpSessionAttributeListener 监听session的种属性变革ServletContextAttributeListenerServletRequestAttributeListenerHttpSessionBindingListener,监听工具存入或者移除 sessionhttpSessionActivationListener,钝化和重新加载 session的监听

三、监听session、request、servletContext

直接上代码,下面监听了这三个工具创建销毁。

public class ListenerTest implements HttpSessionListener ,ServletContextListener,ServletRequestListener{Log log=LogFactory.getLog(getClass());public void requestDestroyed(ServletRequestEvent sre) {HttpServletRequest request=(HttpServletRequest) sre.getServletRequest();long time=System.currentTimeMillis()-(Long)request.getAttribute(\公众time\"大众);log.info(\"大众要求处理韶光\公众+time);}public void requestInitialized(ServletRequestEvent sre) {HttpServletRequest request=(HttpServletRequest) sre.getServletRequest();String uri=request.getRequestURI();uri=request.getQueryString()==null?uri:(uri+\公众?\"大众+request.getQueryString());log.info(\"大众ip\公众+request.getRemoteAddr()+uri);request.setAttribute(\公众time\"大众, System.currentTimeMillis());}public void contextDestroyed(ServletContextEvent sce) {ServletContext servletContext=sce.getServletContext();log.info(\"大众关闭:\"大众+servletContext.getContextPath());}public void contextInitialized(ServletContextEvent sce) {ServletContext servletContext=sce.getServletContext();log.info(\"大众启动:\"大众+servletContext.getContextPath());}public void sessionCreated(HttpSessionEvent se) {HttpSession session=se.getSession();log.info(\"大众创建:session:\"大众+session.getId());}public void sessionDestroyed(HttpSessionEvent se) {HttpSession session=se.getSession();log.info(\公众销毁建:session:\"大众+session.getId());}}

须要在web.xml中配置:

<listener> <listener-class>com.forezp.listener.ListenerTest</listener-class> </listener>

四、监听工具属性的变革

httpSessionAttributeListener 监听session的种属性变革ServletContextAttributeListenerServletRequestAttributeListener

以上三种方法用于监听session ,context,request的属性发生变革,例如添加、更新、移除。
下面以session的属性变革为例子:

public class SessionAttributeListener implements HttpSessionAttributeListener{Log log=LogFactory.getLog(getClass());public void attributeAdded(HttpSessionBindingEvent se) {HttpSession httpSession=se.getSession();log.info(\公众新建属性:\公众+se.getName()+\"大众值:\"大众+se.getValue());}public void attributeRemoved(HttpSessionBindingEvent se) {HttpSession httpSession=se.getSession();log.info(\"大众 删除属性:\"大众+se.getName()+\"大众值:\"大众+se.getValue());}public void attributeReplaced(HttpSessionBindingEvent se) {HttpSession httpSession=se.getSession();log.info(\"大众 修正属性:\"大众+se.getName()+\公众原来的值:\"大众+se.getValue()+\"大众新值:\"大众+httpSession.getAttribute(se.getName()));}}

web.xml配置,此处省略。

五、监听session内的工具

HttpSessionBindingListener,当工具被放到session里实行valueBond();当工具被移除,实行valueUnbond();httpSessionActivationListener,做事器关闭,会将session的内容保存在硬盘里,这个过程叫钝化;做事看重启,会将session的内容从硬盘中重新加载。
钝化时实行sesionWillPassivate(),重新加载sessionDidActivate();

举个例子:

public class User implements HttpSessionBindingListener,HttpSessionActivationListener,Serializable {

private String username;

private String password;

public void valueBound(HttpSessionBindingEvent httpsessionbindingevent) {

System.out.println(\"大众valueBound Name:\"大众+httpsessionbindingevent.getName());

}

public void valueUnbound(HttpSessionBindingEvent httpsessionbindingevent) {

System.out.println(\"大众valueUnbound Name:\公众+httpsessionbindingevent.getName());

}

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

//钝化

public void sessionWillPassivate(HttpSessionEvent httpsessionevent) {

System.out.println(\"大众sessionWillPassivate \"大众+httpsessionevent.getSource());

}

//活化

public void sessionDidActivate(HttpSessionEvent httpsessionevent) {

System.out.println(\公众sessionDidActivate \"大众+httpsessionevent.getSource());

}

}

init.jsp

<%@ page language=\"大众java\"大众 import=\"大众java.util.\公众 pageEncoding=\"大众UTF-8\公众%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+\公众://\"大众+request.getServerName()+\公众:\公众+request.getServerPort()+path+\"大众/\"大众;

request.getSession().setAttribute(\公众currentUser\"大众, new com.forezp.entity.User());

%>

<!DOCTYPE HTML PUBLIC \公众-//W3C//DTD HTML 4.01 Transitional//EN\"大众>

<html>

<head>

<base href=\"大众<%=basePath%>\"大众>

<title>My JSP 'init.jsp' starting page</title>

<meta http-equiv=\公众pragma\"大众 content=\"大众no-cache\公众>

<meta http-equiv=\"大众cache-control\公众 content=\"大众no-cache\公众>

<meta http-equiv=\公众expires\"大众 content=\"大众0\"大众>

<meta http-equiv=\公众keywords\公众 content=\"大众keyword1,keyword2,keyword3\"大众>

<meta http-equiv=\公众description\"大众 content=\"大众This is my page\公众>

<!--

<link rel=\"大众stylesheet\公众 type=\"大众text/css\"大众 href=\"大众styles.css\"大众>

-->

</head>

<body>

这是初始化值的界面

<button onclick=\"大众location.href='<%=request.getContextPath()%>/init.jsp';\"大众>Init</button>

<button onclick=\"大众location.href='<%=request.getContextPath()%>/destory.jsp';\"大众>Destory</button>

</body>

</html>

destroy.jsp

<%@ page language=\"大众java\"大众 import=\公众java.util.\"大众 pageEncoding=\"大众UTF-8\"大众%><%String path = request.getContextPath();String basePath = request.getScheme()+\"大众://\"大众+request.getServerName()+\"大众:\"大众+request.getServerPort()+path+\公众/\"大众;request.getSession().removeAttribute(\公众currentUser\"大众);%><!DOCTYPE HTML PUBLIC \公众-//W3C//DTD HTML 4.01 Transitional//EN\公众><html> <head> <base href=\"大众<%=basePath%>\"大众> <title>My JSP 'destory.jsp' starting page</title> <meta http-equiv=\"大众pragma\公众 content=\"大众no-cache\"大众><meta http-equiv=\"大众cache-control\"大众 content=\"大众no-cache\公众><meta http-equiv=\"大众expires\"大众 content=\公众0\公众> <meta http-equiv=\"大众keywords\公众 content=\"大众keyword1,keyword2,keyword3\"大众><meta http-equiv=\"大众description\"大众 content=\公众This is my page\"大众><!--<link rel=\"大众stylesheet\"大众 type=\公众text/css\"大众 href=\"大众styles.css\"大众>--> </head> <body> 这是销毁界面 <button onclick=\"大众location.href='<%=request.getContextPath()%>/init.jsp';\公众>Init</button> <button onclick=\"大众location.href='<%=request.getContextPath()%>/destory.jsp';\"大众>Destory</button> </body></html>

当访问init.jsp,再访问destroy.jsp;再访问init,jsp,再关闭做事器,重启;log日志如下:

valueBound Name:currentUser

valueUnbound Name:currentUser

sessionWillPassivate org.apache.catalina.session.StandardSessionFacade@33f3be1

sessionDidActivate org.apache.catalina.session.StandardSessionFacade@33f3be1

六、显示在线人数:

@WebListenerpublic class MyHttpSessionListener implements HttpSessionListener {private int userNumber = 0;@Overridepublic void sessionCreated(HttpSessionEvent arg0) {userNumber++;arg0.getSession().getServletContext().setAttribute(\"大众userNumber\公众, userNumber);}@Overridepublic void sessionDestroyed(HttpSessionEvent arg0) {userNumber--;arg0.getSession().getServletContext().setAttribute(\"大众userNumber\"大众, userNumber);}}

jsp中显示:

<body> 当前在线用户人数:${userNumber }<br/></body>

这是一个简答的统计在线人数的方法,如果你须要知道这些人来自哪里,须要合营httpRequestListener合营,也可以实现单上岸,在这里不写代码了。