监听器
Servlet中的相关监听器
在其相关对象(ServletContext、HttpSession、ServletRequest)创建、销毁或者对其属性进行操作时会触发监听。
根据要实现的功能选择实现要监听的接口并配置。
Servlet中的相关的监听器
Object | Event | Listener Interface and Event Class |
---|---|---|
Web Context | Initialization and destruction | javax.servlet.ServletContextListener and ServletContextEvent |
Web Context | Attribute, added, removed, or replaced | javax.servlet.ServletContextAttributeListener and ServletContextAttributeEvent |
Session | creation, invalidation, activation, passivation, timeout | javax.servlet.http.HttpSessionListener, javax.servlet.http.HttpSessionActivationListener, and HttpSessionEvent |
Session | Attribute, added, removed, or replaced | javax.servlet.http.HttpSessionAttributeListener, HttpSessionBindingEvent |
Request | A servlet request has started being processed by web components | javax.servlet.ServletRequestListener and ServletRequestEvent |
Request | Attribute added, removed, or replaced | javax.servlet.ServletRequestAttributeListener and ServletRequestAttributeEvent |
示例程序
WebContextListener.java
package com.li.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/*
* 通过实现WebContextListener接口并在web.xml中配置,来对WebContext进行监听
*/
public class WebContextListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent event) {
System.out.println("WebContextListener contextDestroyed "+event.getServletContext());
}
@Override
public void contextInitialized(ServletContextEvent event) {
System.out.println("WebContextListener contextInitialized "+event.getServletContext());
}
}
WebContextAttrListener.java
package com.li.listener;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
/*对WebContext的Attribute这一属性进行监听*/
public class WebContextAttrListener implements ServletContextAttributeListener {
@Override
public void attributeAdded(ServletContextAttributeEvent event) {
System.out.println("WebContextAttributeListener added name:"+event.getName()+" value: "+event.getValue());
}
@Override
public void attributeRemoved(ServletContextAttributeEvent event) {
System.out.println("WebContextAttributeListener removed name:"+event.getName()+" value: "+event.getValue());
}
@Override
public void attributeReplaced(ServletContextAttributeEvent event) {
System.out.println("WebContextAttributeListener replaceed name:"+event.getName()+" value: "+event.getValue());
}
}
SessionListener.java
package com.li.listener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/*对Session进行监听*/
public class SessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent event) {
System.out.println("SessionListener created "+event.getSession());
}
@Override
public void sessionDestroyed(HttpSessionEvent event) {
System.out.println("SessionListener destoryed "+event.getSession());
}
}
SessionAttrListener.java
package com.li.listener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
public class SessionAttrListener implements HttpSessionAttributeListener {
@Override
public void attributeAdded(HttpSessionBindingEvent event) {
System.out.println("SessionAttributeListener added name:"+event.getName()+" value: "+event.getValue());
}
@Override
public void attributeRemoved(HttpSessionBindingEvent event) {
System.out.println("SessionAttributeListener removed name:"+event.getName()+" value: "+event.getValue());
}
@Override
public void attributeReplaced(HttpSessionBindingEvent event) {
System.out.println("SessionAttributeListener replaced name:"+event.getName()+" value: "+event.getValue());
}
}
RequestListener.java
package com.li.listener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
public class RequestListener implements ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent event) {
System.out.println("RequestListener destroy "+event.getServletRequest());
}
@Override
public void requestInitialized(ServletRequestEvent event) {
System.out.println("RequestListener init "+event.getServletRequest());
}
}
RequestAttrListener.java
package com.li.listener;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
public class RequestAttrListener implements ServletRequestAttributeListener {
@Override
public void attributeAdded(ServletRequestAttributeEvent event) {
System.out.println("RequestAttributeListener added name:"+event.getName()+" value: "+event.getValue());
}
@Override
public void attributeRemoved(ServletRequestAttributeEvent event) {
System.out.println("RequestAttributeListener removeed name:"+event.getName()+" value: "+event.getValue());
}
@Override
public void attributeReplaced(ServletRequestAttributeEvent event) {
System.out.println("RequestAttributeListener replaceed name:"+event.getName()+" value: "+event.getValue());
}
}
测试服务(BindAttrServlet.java)
package com.li.listener;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class BindAttrServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//直接获取ServletContext
ServletContext context=getServletContext();
System.out.println("ServletContext add");
context.setAttribute("context", "test-add"); //添加操作
System.out.println("ServletContext added");
System.out.println("ServletContext replace");
context.setAttribute("context", "test-replace"); //替换操作
System.out.println("ServletContext replaced");
System.out.println("ServletContext remove");
context.removeAttribute("context"); //移除操作
System.out.println("ServletContxt removed");
System.out.println("---------------");
HttpSession session=req.getSession();
System.out.println("Session add");
session.setAttribute("session", "test-add");
System.out.println("Session added");
System.out.println("Session replace");
context.setAttribute("session", "test-replace");
System.out.println("Session replaced");
System.out.println("Session remove");
context.removeAttribute("session");
System.out.println("Session removed");
System.out.println("---------------");
System.out.println("Request add");
session.setAttribute("request", "test-add");
System.out.println("Request added");
System.out.println("Request replace");
context.setAttribute("request", "test-replace");
System.out.println("Request replaced");
System.out.println("Request remove");
context.removeAttribute("request");
System.out.println("Request removed");
}
}
HTML(index.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="bindAttr">请求Servlet</a>
</body>
</html>
配置文件(web.xml)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>ProcessingForms</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<listener>
<listener-class>com.li.listener.WebContextListener</listener-class>
</listener>
<listener>
<listener-class>com.li.listener.WebContextAttrListener</listener-class>
</listener>
<listener>
<listener-class>com.li.listener.SessionListener</listener-class>
</listener>
<listener>
<listener-class>com.li.listener.SessionAttrListener</listener-class>
</listener>
<listener>
<listener-class>com.li.listener.RequestListener</listener-class>
</listener>
<listener>
<listener-class>com.li.listener.RequestAttrListener</listener-class>
</listener>
<servlet>
<servlet-name>BindAttr</servlet-name>
<servlet-class>com.li.listener.BindAttrServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BindAttr</servlet-name>
<url-pattern>/bindAttr</url-pattern>
</servlet-mapping>
</web-app>
启动Tomcat,我们能够观察到,WebContext在服务器启动的时候就已经先自动创建,待我们打开应用首页,一个Request又经历了创建,替换,销毁三个阶段,我们点击链接,接下来我们可以看到各个监听的执行。
通过网站的在线客户数
用户第一次访问时总数加一(不允许重复增加)
在用户退出时(Session)过期时总数减一
实现HttpSessionListener
配置监听(我们可以通过代买在配置文件中配置Session的最大过期时间,Tomcat默认的额过期时间是30分钟,在Tomcat的servers的配置文件中,过期时间配置单位是分钟,我们自己配置时间的单位是秒)
<!-- ==================== Default Session Configuration ================= --> <!-- You can set the default session timeout (in minutes) for all newly --> <!-- created sessions by modifying the value below. --> <session-config> <session-timeout>30</session-timeout> </session-config>
示例代码
统计服务程序(SessionListener.java)
package com.li.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/*通过SessionListener来统计在线人数,人数适合保存在ServletContext中*/
public class SessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent event) {
HttpSession session=event.getSession();
/*让Session立马过期销毁掉:session.invalidate()*/
/*设置Session的最大间隔时间,单位是秒:session.setMaxInactiveInterval(30)*/
ServletContext context=session.getServletContext();
Integer number=(Integer)context.getAttribute("total");
if(number==null) {
context.setAttribute("total", 1);
}
else {
context.setAttribute("total", number+1);
}
}
@Override
public void sessionDestroyed(HttpSessionEvent event) {
HttpSession session=event.getSession();
ServletContext context=session.getServletContext();
Integer number=(Integer)context.getAttribute("total");
context.setAttribute("total", number-1);
}
}
信息显示程序(ShowServlet.java)
package com.li.servlet;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ShowServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session=req.getSession();
ServletContext cxt=getServletContext();
Integer number=(Integer)cxt.getAttribute("total");
resp.setContentType("text/html; charset=UTF-8");
if(number != null) {
resp.getWriter().write("<h3>当前的用户数量是:"+number+"</h3>");
}
/*再设置一个超链接来刷新:超链接仍然访问的是此服务*/
resp.getWriter().write("<a href='show'>刷新</a>");
}
}
主页(index.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="show">查看在线人数</a>
</body>
</html>
配置文件(web.xml)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>OnlineNumber</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<!-- 在配置文件中设置session的最大间隔时间,单位是分钟 -->
<session-config>
<session-timeout>1</session-timeout>
</session-config>
<listener>
<listener-class>com.li.listener.SessionListener</listener-class>
</listener>
<servlet>
<servlet-name>ShowServlet</servlet-name>
<servlet-class>com.li.servlet.ShowServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShowServlet</servlet-name>
<url-pattern>/show</url-pattern>
</servlet-mapping>
</web-app>