JavaWeb中的监听器
l 事件源:三大域!
Ø ServletContext(在服务器启动时生,在服务器停止时它才死)
¨ 生命周期监听:ServletContextListener,它有两个方法,一个在出生时调用,一个在死亡时调用;
² void contextInitialized(ServletContextEvent sce):创建SErvletcontext时
² void contextDestroyed(ServletContextEvent sce):销毁Servletcontext时
¨ 属性监听:ServletContextAttributeListener,它有三个方法,一个在添加属性时调用,一个在替换属性时调用,最后一个是在移除属性时调用。
² void attributeAdded(ServletContextAttributeEvent event):添加属性时;
² void attributeReplaced(ServletContextAttributeEvent event):替换属性时;
² void attributeRemoved(ServletContextAttributeEvent event):移除属性时;
Ø HttpSession(浏览器没有访问就没有session,但是即使是浏览器访问,在代码中必须有request.getSession() 才有session)
¨ 生命周期监听:HttpSessionListener,它有两个方法,一个在出生时调用,一个在死亡时调用;
² void sessionCreated(HttpSessionEvent se):创建session时
² void sessionDestroyed(HttpSessionEvent se):销毁session时
¨ 属性监听:HttpSessioniAttributeListener,它有三个方法,一个在添加属性时调用,一个在替换属性时调用,最后一个是在移除属性时调用。
² void attributeAdded(HttpSessionBindingEvent event):添加属性时;
² void attributeReplaced(HttpSessionBindingEvent event):替换属性时
² void attributeRemoved(HttpSessionBindingEvent event):移除属性时
Ø ServletRequest(在请求发出的时候,就创建一遍,再发一次请求就右创建一次,如果请求的是静态资源不会创建)
¨ 生命周期监听:ServletRequestListener,它有两个方法,一个在出生时调用,一个在死亡时调用;
² void requestInitialized(ServletRequestEvent sre):创建request时
² void requestDestroyed(ServletRequestEvent sre):销毁request时
¨ 属性监听:ServletRequestAttributeListener,它有三个方法,一个在添加属性时调用,一个在替换属性时调用,最后一个是在移除属性时调用。
² void attributeAdded(ServletRequestAttributeEvent srae):添加属性时
² void attributeReplaced(ServletRequestAttributeEvent srae):替换属性时
² void attributeRemoved(ServletRequestAttributeEvent srae):移除属性时
javaWeb中完成编写监听器:
Ø 写一个监听器类:要求必须去实现某个监听器接口;
Ø 注册,是在web.xml中配置来完成注册!
package cn.itcast.web.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* ServletContext生死监听
* @author cxf
*
* 可以在这个监听器存放一些在tomcat启动时就要完成的代码!
*/
public class AListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("servletContext 在启动服务器后调用");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("servletContext 在服务器停止之前调用");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<listener>
<listener-class>cn.itcast.web.listener.AListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
这个时候启动服务器
七月 13, 2018 3:23:55 下午 org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=E:\software\tomcat\apache-tomcat-7.0.82-windows-x64\apache-tomcat-7.0.82\endorsed
七月 13, 2018 3:23:55 下午 org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=GBK
七月 13, 2018 3:23:55 下午 org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: E:\setuppath\Java\jdk1.7.0_17\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program Files (x86)\Common Files\NetSarang;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;E:\setuppath\Java\jdk1.7.0_17\bin;E:\setuppath\Java\jdk1.7.0_17\jre\bin;.
七月 13, 2018 3:23:55 下午 org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
七月 13, 2018 3:23:56 下午 org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
七月 13, 2018 3:23:56 下午 org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 3621 ms
七月 13, 2018 3:23:56 下午 org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
七月 13, 2018 3:23:56 下午 org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.82
servletContext 在启动服务器后调用
您向application中添加了一个名为org.apache.jasper.compiler.TldLocationsCache, 值为:org.apache.jasper.compiler.TldLocationsCache@3205bd66的属性
七月 13, 2018 3:23:57 下午 org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
七月 13, 2018 3:23:57 下午 org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
七月 13, 2018 3:23:57 下午 org.apache.catalina.startup.Catalina start
INFO: Server startup in 1442 ms
七月 13, 2018 3:23:57 下午 org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
七月 13, 2018 3:23:57 下午 org.apache.catalina.startup.Catalina start
INFO: Server startup in 1442 ms
七月 13, 2018 3:25:07 下午 org.apache.catalina.core.StandardServer await
INFO: A valid shutdown command was received via the shutdown port. Stopping the Server instance.
七月 13, 2018 3:25:07 下午 org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["http-bio-8080"]
七月 13, 2018 3:25:07 下午 org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["ajp-bio-8009"]
七月 13, 2018 3:25:07 下午 org.apache.catalina.core.StandardService stopInternal
INFO: Stopping service Catalina
servletContext 在服务器停止之前调用
七月 13, 2018 3:25:07 下午 org.apache.coyote.AbstractProtocol stop
INFO: Stopping ProtocolHandler ["http-bio-8080"]
七月 13, 2018 3:25:07 下午 org.apache.coyote.AbstractProtocol stop
INFO: Stopping ProtocolHandler ["ajp-bio-8009"]
七月 13, 2018 3:25:07 下午 org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["http-bio-8080"]
七月 13, 2018 3:25:07 下午 org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["ajp-bio-8009"]
/*
* ServletContextListener实现类
* contextDestroyed() -- 在ServletContext对象被销毁前调用
* contextInitialized() -- -- 在ServletContext对象被创建后调用
* ServletContextEvent -- 事件类对象
* 该类有getServletContext(),用来获取ServletContext对象,即获取事件源对象
*/
public class MyServletContextListener implements ServletContextListener {
public void contextDestroyed(ServletContextEvent evt) {
System.out.println("销毁ServletContext对象");
}
public void contextInitialized(ServletContextEvent evt) {
System.out.println("创建ServletContext对象");
}
}
/*
* HttpSessionListener实现类
* sessionCreated() -- 在HttpSession对象被创建后被调用
* sessionDestroyed() -- -- 在HttpSession对象被销毁前调用
* HttpSessionEvent -- 事件类对象
* 该类有getSession(),用来获取当前HttpSession对象,即获取事件源对象
*/
public class MyHttpSessionListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent evt) {
System.out.println("创建session对象");
}
public void sessionDestroyed(HttpSessionEvent evt) {
System.out.println("销毁session对象");
}
}
/*
* ServletRequestListener实现类
* requestDestroyed() -- 在ServletRequest对象被销毁前调用
* requestInitialized() -- 在ServletRequest对象被创建后调用
* ServletRequestEvent -- 事件类对象
* 该类有getServletContext(),用来获取ServletContext对象
* 该类有getServletRequest(),用来获取当前ServletRequest对象,即事件源对象
*/
public class MyServletRequestListener implements ServletRequestListener {
public void requestDestroyed(ServletRequestEvent evt) {
System.out.println("销毁request对象");
}
public void requestInitialized(ServletRequestEvent evt) {
System.out.println("创建request对象");
}
}
<listener>
<listener-class>cn.itcast.listener.MyServletContextListener</listener-class>
</listener>
<listener>
<listener-class>cn.itcast.listener.MyHttpSessionListener</listener-class>
</listener>
<listener>
<listener-class>cn.itcast.listener.MyServletRequestListener</listener-class>
</listener>
<session-config>
<session-timeout>1</session-timeout>
</session-config>
servletContext 属性监听有三种(添加,替换,移除)
package cn.itcast.web.listener;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
public class BListener implements ServletContextAttributeListener {
public void attributeAdded(ServletContextAttributeEvent scab) {
System.out.println("您向application中添加了一个名为" + scab.getName() + ", 值为:"
+ scab.getValue() + "的属性");
}
public void attributeReplaced(ServletContextAttributeEvent scab) {
System.out.println(scab.getName() + "=" + scab.getValue() + ", "
+ scab.getServletContext().getAttribute(scab.getName()));
}
public void attributeRemoved(ServletContextAttributeEvent scab) {
System.out.println(scab.getName() + "=" + scab.getValue());
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<listener>
<listener-class>cn.itcast.web.listener.AListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>cn.itcast.web.listener.BListener</listener-class>
</listener>
</web-app>
index.jsp(保存属性application.setAttribute("xxx", "XXX"));
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.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>
<%
application.setAttribute("xxx", "XXX");
%>
</body>
</html>
replace.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.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>
<%
application.setAttribute("xxx", "kkk");
%>
</body>
</html>
remove.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.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>
<%
application.removeAttribute("xxx");
%>
</body>
</html>
您向application中添加了一个名为org.apache.jasper.compiler.TldLocationsCache, 值为:org.apache.jasper.compiler.TldLocationsCache@14bc5c96的属性
七月 13, 2018 4:07:38 下午 org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
七月 13, 2018 4:07:38 下午 org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
七月 13, 2018 4:07:38 下午 org.apache.catalina.startup.Catalina start
INFO: Server startup in 493 ms
您向application中添加了一个名为org.apache.jasper.runtime.JspApplicationContextImpl, 值为:org.apache.jasper.runtime.JspApplicationContextImpl@47fa7bd5的属性
您向application中添加了一个名为xxx, 值为:XXX的属性
七月 13, 2018 4:07:38 下午 org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
七月 13, 2018 4:07:38 下午 org.apache.catalina.startup.Catalina start
INFO: Server startup in 493 ms
您向application中添加了一个名为org.apache.jasper.runtime.JspApplicationContextImpl, 值为:org.apache.jasper.runtime.JspApplicationContextImpl@47fa7bd5的属性
您向application中添加了一个名为xxx, 值为:XXX的属性
老值:xxx=XXX, 新值:kkk
七月 13, 2018 4:07:37 下午 org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.82
servletContext 在启动服务器后调用
您向application中添加了一个名为org.apache.jasper.compiler.TldLocationsCache, 值为:org.apache.jasper.compiler.TldLocationsCache@14bc5c96的属性
七月 13, 2018 4:07:38 下午 org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
七月 13, 2018 4:07:38 下午 org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
七月 13, 2018 4:07:38 下午 org.apache.catalina.startup.Catalina start
INFO: Server startup in 493 ms
您向application中添加了一个名为org.apache.jasper.runtime.JspApplicationContextImpl, 值为:org.apache.jasper.runtime.JspApplicationContextImpl@47fa7bd5的属性
您向application中添加了一个名为xxx, 值为:XXX的属性
老值:xxx=XXX, 新值:kkk
老值:xxx=kkk, 新值:kkk
老值:xxx=kkk, 新值:kkk
您向application中添加了一个名为org.apache.jasper.compiler.ELInterpreter, 值为:org.apache.jasper.compiler.ELInterpreterFactory$DefaultELInterpreter@77157ae0的属性
xxx=kkk 表示已经删除了
public class MyListener implements ServletContextAttributeListener,
ServletRequestAttributeListener, HttpSessionAttributeListener {
public void attributeAdded(HttpSessionBindingEvent evt) {
System.out.println("向session中添加属性:" + evt.getName() + "=" + evt.getValue());
}
public void attributeRemoved(HttpSessionBindingEvent evt) {
System.out.println("从session中移除属性:" + evt.getName() + "=" + evt.getValue());
}
public void attributeReplaced(HttpSessionBindingEvent evt) {
System.out.println("修改session中的属性:" + evt.getName() + "=" + evt.getValue());
}
public void attributeAdded(ServletRequestAttributeEvent evt) {
System.out.println("向request中添加属性:" + evt.getName() + "=" + evt.getValue());
}
public void attributeRemoved(ServletRequestAttributeEvent evt) {
System.out.println("从request中移除属性:" + evt.getName() + "=" + evt.getValue());
}
public void attributeReplaced(ServletRequestAttributeEvent evt) {
System.out.println("修改request中的属性:" + evt.getName() + "=" + evt.getValue());
}
public void attributeAdded(ServletContextAttributeEvent evt) {
System.out.println("向context中添加属性:" + evt.getName() + "=" + evt.getValue());
}
public void attributeRemoved(ServletContextAttributeEvent evt) {
System.out.println("从context中移除属性:" + evt.getName() + "=" + evt.getValue());
}
public void attributeReplaced(ServletContextAttributeEvent evt) {
System.out.println("修改context中的属性:" + evt.getName() + "=" + evt.getValue());
}
}
public class ListenerServlet extends BaseServlet {
public String contextOperation(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext context = this.getServletContext();
context.setAttribute("a", "a");
context.setAttribute("a", "A");
context.removeAttribute("a");
return "/index.jsp";
}
///////////////////////////////
public String sessionOperation(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
session.setAttribute("a", "a");
session.setAttribute("a", "A");
session.removeAttribute("a");
return "/index.jsp";
}
///////////////////////////////
public String requestOperation(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("a", "a");
request.setAttribute("a", "A");
request.removeAttribute("a");
return "/index.jsp";
}
}
<body>
<a href="<c:url value='/ListenerServlet?method=contextOperation'/>">SevletContext操作属性</a>
<br/>
<a href="<c:url value='/ListenerServlet?method=sessionOperation'/>">HttpSession操作属性</a>
<br/>
<a href="<c:url value='/ListenerServlet?method=requestOperation'/>">ServletRequest操作属性</a> |
</body>
事件对象(8个):
Ø ServletContextEvent:ServletContext getServletContext()
Ø HttpSessionEvent:HttpSession getSession()
Ø ServletRequest:
¨ ServletContextgetServletContext();
¨ ServletRequesgetServletRequest();
Ø ServletContextAttributeEvent:
¨ ServletContextgetServletContext();
¨ StringgetName():获取属性名
¨ ObjectgetValue():获取属性值
Ø ServletRequestAttributeEvent :略
HttpSession 监听器
另外两个监听对象是感知监听(都与HttpSession相关)
它用来添加到JavaBean上,而不是添加到三大域上!
这两个监听器都不需要在web.xml中注册!
HttpSessionBindingListener:添加到javabean上,javabean就知道自己是否添加到session中了。
package cn.itcast.web.listener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
public class User implements HttpSessionBindingListener {
private String username;
private String password;
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 User() {
super();
// TODO Auto-generated constructor stub
}
public User(String username, String password) {
super();
this.username = username;
this.password = password;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + "]";
}
@Override
public void valueBound(HttpSessionBindingEvent event) {
System.out.println("啊~,session添加了我!");
}
@Override
public void valueUnbound(HttpSessionBindingEvent event) {
System.out.println("哇哇哇~,无情的session抛弃了我!");
}
}
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'add.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>
<%
cn.itcast.web.listener.User user = new cn.itcast.web.listener.User();
session.setAttribute("user", user);
%>
</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'remove.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>
<%
session.removeAttribute("user");
%>
</body>
</html>
您向application中添加了一个名为org.apache.jasper.compiler.TldLocationsCache, 值为:org.apache.jasper.compiler.TldLocationsCache@d5a2e07的属性
七月 13, 2018 4:30:41 下午 org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
七月 13, 2018 4:30:41 下午 org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
七月 13, 2018 4:30:41 下午 org.apache.catalina.startup.Catalina start
INFO: Server startup in 491 ms
您向application中添加了一个名为org.apache.jasper.runtime.JspApplicationContextImpl, 值为:org.apache.jasper.runtime.JspApplicationContextImpl@5d8ea8df的属性
啊~,session添加了我!
servletContext 在启动服务器后调用
您向application中添加了一个名为org.apache.jasper.compiler.TldLocationsCache, 值为:org.apache.jasper.compiler.TldLocationsCache@d5a2e07的属性
七月 13, 2018 4:30:41 下午 org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
七月 13, 2018 4:30:41 下午 org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
七月 13, 2018 4:30:41 下午 org.apache.catalina.startup.Catalina start
INFO: Server startup in 491 ms
您向application中添加了一个名为org.apache.jasper.runtime.JspApplicationContextImpl, 值为:org.apache.jasper.runtime.JspApplicationContextImpl@5d8ea8df的属性
啊~,session添加了我!
您向application中添加了一个名为org.apache.jasper.compiler.ELInterpreter, 值为:org.apache.jasper.compiler.ELInterpreterFactory$DefaultELInterpreter@558aeea2的属性
哇哇哇~,无情的session抛弃了我!