1.8(学习笔记)监听器(Listener)
一、監(jiān)聽器簡(jiǎn)介
監(jiān)聽器是web容器對(duì)某一些對(duì)象的監(jiān)聽,當(dāng)某些對(duì)象發(fā)生創(chuàng)建、修改、刪除的動(dòng)作時(shí),
web容器會(huì)自動(dòng)調(diào)用對(duì)應(yīng)的監(jiān)聽器中的方法。
例如A是監(jiān)聽器,B是被監(jiān)聽對(duì)象,A的監(jiān)聽任務(wù)是B回家時(shí)來開門。
那么當(dāng)B一回家,監(jiān)聽器A就會(huì)執(zhí)行開門的操作。
?
二、監(jiān)聽器用法
2.1.1 ServletContextListener
用于監(jiān)聽ServletContext對(duì)象的創(chuàng)建及銷毀,實(shí)際上就是監(jiān)聽Web應(yīng)用的生命周期。
首先我們要?jiǎng)?chuàng)建一個(gè)類,實(shí)現(xiàn)ServletContextListener接口,實(shí)現(xiàn)里面的兩個(gè)方法:
public void contextInitialized(ServletContextEvent sce)//web程序初始化時(shí)執(zhí)行
public void contextDestroyed(ServletContextEvent sce)//web程序銷毀時(shí)執(zhí)行
?
ContextListener:
import java.io.PrintStream;import javax.servlet.ServletContextEvent;public class ServletContextListener implements javax.servlet.ServletContextListener{PrintStream out = System.out;@Overridepublic void contextInitialized(ServletContextEvent sce) {// TODO Auto-generated method stubout.println("ContextInit");}@Overridepublic void contextDestroyed(ServletContextEvent sce) {// TODO Auto-generated method stubout.println("ContextDestroyed");} }web.xml
<listener><listener-class>com.listener.ServletContextListener</listener-class></listener>當(dāng)打開Tomcat時(shí),監(jiān)聽器監(jiān)聽到ServletContext開始初始化,會(huì)執(zhí)行contextInitialized(),
打印出ContextInit。當(dāng)關(guān)閉Tomcat時(shí),監(jiān)聽器監(jiān)聽到ServeltContext已關(guān)閉,會(huì)執(zhí)行contextDestroyed(),
打印出ContextDestroyed.
? ? ??
?
2.1.2ServletContextAttrubute
監(jiān)聽ServletContext屬性列表發(fā)送更改。
比如屬性的添加(setAttrubute("a","a")、
修改(setAttribute("a","A"))、刪除(removeAttribute("a"))。
ServletContextAttribute中有三個(gè)方法:
attributeAdded(ServletContextAttributeEvent scae);//監(jiān)聽添加屬性
attributeRemoved(ServletContextAttributeEvent scae)//監(jiān)聽刪除屬性
attributeReplaced(ServletContextAttributeEvent scae)//監(jiān)聽修改屬性
?
import java.io.PrintStream;import javax.servlet.ServletContextAttributeEvent; import javax.servlet.ServletContextAttributeListener; import javax.servlet.ServletContextEvent;public class ServletContextListener implements ServletContextAttributeListener{PrintStream out = System.out;@Overridepublic void attributeAdded(ServletContextAttributeEvent scae) {// TODO Auto-generated method stubout.println("AddAttribute");}@Overridepublic void attributeRemoved(ServletContextAttributeEvent scae) {// TODO Auto-generated method stubout.println("RemovedAttribute");}@Overridepublic void attributeReplaced(ServletContextAttributeEvent scae) {// TODO Auto-generated method stubout.println("ReplacedAddAttribute");} }?
LoginServlet:
import java.io.IOException; import java.io.PrintWriter;import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;import com.util.HttpPageUtil;public class LoginServlet extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {PrintWriter out = response.getWriter();String username = request.getParameter("username");ServletContext sc = this.getServletContext();//添加sc.setAttribute("Attribute", "addAttribute");//修改sc.setAttribute("Attribute", "reAttribute");//刪除sc.removeAttribute("Attribute");HttpPageUtil.printHtmlPage(out, true);out.println("SerlvetContextAttribute");HttpPageUtil.printHtmlPage(out, false);System.out.println("Servlet");}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub doGet(request, response);} }控制臺(tái)輸出:
當(dāng)LoginServlet中向ServletContext添加屬性時(shí),對(duì)應(yīng)監(jiān)聽器監(jiān)聽到添加動(dòng)作,
執(zhí)行方法attributeAdded()方法輸出AddAttribute,修改屬性時(shí)執(zhí)行attributeReplaced()方法
輸出ReplacedAddAttribute,刪除屬性時(shí)執(zhí)行attributeRemoved()方法,輸出RemoveAttribute。
?
2.2.1HttpSessionListener
HttpSessionnLister主要用于監(jiān)聽Session的創(chuàng)建及銷毀。
? ? ?public void sessionCreated(HttpSessionEvent se)//session創(chuàng)建時(shí)執(zhí)行。
public void sessionDestroyed(HttpSessionEvent se)//session銷毀時(shí)執(zhí)行。
?
import java.io.PrintStream;import javax.servlet.http.HttpSessionEvent;public class HttpSessionListener implements javax.servlet.http.HttpSessionListener{PrintStream out = System.out;@Overridepublic void sessionCreated(HttpSessionEvent se) {// TODO Auto-generated method stubout.println("SeesionCreater");}@Overridepublic void sessionDestroyed(HttpSessionEvent se) {// TODO Auto-generated method stubout.println("SeesionDestroy");}}控制臺(tái)輸出:
但Session創(chuàng)建銷毀時(shí),監(jiān)聽器會(huì)監(jiān)聽到對(duì)應(yīng)的動(dòng)作并執(zhí)行對(duì)方法。
?
2.2.2HttpSessionAttributeListener
主要監(jiān)聽Session對(duì)象屬性的添加、修改、刪除操作。
public void attributeAdded(HttpSessionBindingEvent se);//添加session中屬性時(shí)執(zhí)行
public void attributeRemoved(HttpSessionBindingEvent se);//刪除session中屬性時(shí)執(zhí)行
public void attributeReplaced(HttpSessionBindingEvent se);//修改session中屬性時(shí)執(zhí)行
?
HttpSessionAttributeListener public class HttpSessionListener implements javax.servlet.http.HttpSessionAttributeListener{PrintStream out = System.out;@Overridepublic void attributeAdded(HttpSessionBindingEvent se) {// TODO Auto-generated method stubout.println("SessionAttributeAdd");}@Overridepublic void attributeRemoved(HttpSessionBindingEvent se) {// TODO Auto-generated method stubout.println("SessionAttributeRemove");}@Overridepublic void attributeReplaced(HttpSessionBindingEvent se) {// TODO Auto-generated method stubout.println("SessionAttributeReplace");}}?
LoginServlet?
import java.io.IOException; import java.io.PrintWriter;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;import com.util.HttpPageUtil;;// http://localhost:8080/TestServlet/Filter/Login public class LoginServlet extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {PrintWriter out = response.getWriter();String username = request.getParameter("username");HttpSession session = request.getSession();//添加session.setAttribute("attribute", "add");//修改session.setAttribute("attribute", "replace");//刪除session.removeAttribute("attribute");HttpPageUtil.printHtmlPage(out, true);out.println("SessionAttributeListener");HttpPageUtil.printHtmlPage(out, false);System.out.println("Servlet");}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub doGet(request, response);} }控制臺(tái)輸出:
監(jiān)聽器會(huì)添加session中屬性的增加、修改、刪除,并執(zhí)行對(duì)應(yīng)方法
輸出對(duì)應(yīng)方法中的語句。
?
2.3.1ServletRequestListener
ServletRequestListener主要監(jiān)聽request的初始化和銷毀。
public void requestDestroyed(ServletRequestEvent sre);//request初始化時(shí)執(zhí)行。
public void requestInitialized(ServletRequestEvent sre);//request銷毀時(shí)執(zhí)行。
?
import java.io.PrintStream;import javax.servlet.ServletRequestEvent;public class ServletRequest implements javax.servlet.ServletRequestListener{PrintStream out = System.out;@Overridepublic void requestDestroyed(ServletRequestEvent sre) {// TODO Auto-generated method stubout.println("RequestDestroy");}@Overridepublic void requestInitialized(ServletRequestEvent sre) {// TODO Auto-generated method stubout.println("RequestInit");} }?
LoginServlet:
import java.io.IOException; import java.io.PrintWriter;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;import com.util.HttpPageUtil;;// http://localhost:8080/TestServlet/Filter/Login public class LoginServlet extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("intoServlet");}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub doGet(request, response);} }但在地址欄通過URL訪問LoginServlet時(shí):
控制臺(tái)輸出結(jié)果:
當(dāng)發(fā)送一個(gè)訪問請(qǐng)求時(shí),請(qǐng)求初始化被監(jiān)聽器監(jiān)聽到,執(zhí)行對(duì)應(yīng)方法輸出“RequestInit”。
然后到達(dá)LoginServlet進(jìn)行輸出"intoServlet",最后請(qǐng)求結(jié)束被監(jiān)聽器監(jiān)聽到,執(zhí)行requestDestroyed方法
輸出“RequestDestroy”。
?
2.3.2 ServletRequestAttributeListener
ServletResqeustAttributerListener主要監(jiān)聽reques中屬性的創(chuàng)建、修改、刪除。
public void attributeAdded(HttpSessionBindingEvent se);//添加session中屬性時(shí)執(zhí)行
public void attributeRemoved(HttpSessionBindingEvent se);//刪除session中屬性時(shí)執(zhí)行
public void attributeReplaced(HttpSessionBindingEvent se);//修改session中屬性時(shí)執(zhí)行
?
RequestAttributeListener:
import java.io.PrintStream;import javax.servlet.ServletRequestAttributeEvent;public class ServletRequest implements javax.servlet.ServletRequestAttributeListener{PrintStream out = System.out;@Overridepublic void attributeAdded(ServletRequestAttributeEvent srae) {// TODO Auto-generated method stubout.println("AddAttribute");}@Overridepublic void attributeRemoved(ServletRequestAttributeEvent srae) {// TODO Auto-generated method stub out.println("RemoveAttribute");}@Overridepublic void attributeReplaced(ServletRequestAttributeEvent srae) {// TODO Auto-generated method stubout.println("ReplaceAttribute");} }?
LoginServlet:
?
import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;import com.util.HttpPageUtil;; public class LoginServlet extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//添加request.setAttribute("attribute", "add");//修改request.setAttribute("attribute", "replace");//刪除request.removeAttribute("attribute");}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub doGet(request, response);} }通過URL調(diào)用LoginServlet,
控制臺(tái)輸出:
當(dāng)在reques中設(shè)置屬性時(shí),對(duì)應(yīng)監(jiān)聽器會(huì)監(jiān)聽到,并調(diào)用attributeAdded()方法,輸出"AddAttribute".
當(dāng)修改reqest中屬性時(shí),會(huì)調(diào)用attributeReplaced()方法,輸出“ReplaceAttribute”.
當(dāng)刪除reques中屬性時(shí)會(huì)嗲用attributeRemoved()方法,輸出“RemoveAttribute”。
?
三、監(jiān)聽器實(shí)例(在線人數(shù)統(tǒng)計(jì))
? 首先在線人數(shù)應(yīng)該是全站可見的,所以人數(shù)應(yīng)該存放在作用域最大的ServletContexte中。
每登入一個(gè)用戶我們就創(chuàng)建一個(gè)Session,Session監(jiān)聽器中人數(shù)+1。當(dāng)一個(gè)session銷毀時(shí)
監(jiān)聽器中人數(shù)-1.
?
OnLineListener:
import java.util.Set; import java.util.TreeSet;import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.http.HttpSessionEvent;public class OnLineListener implements javax.servlet.ServletContextListener, javax.servlet.http.HttpSessionListener{private ServletContext sc = null;private int count = 0;//記錄登陸人數(shù) @Overridepublic void sessionCreated(HttpSessionEvent se) {// TODO Auto-generated method stub//當(dāng)創(chuàng)建用戶session時(shí),count++count++;//將人數(shù)設(shè)置在ServletContext中sc.setAttribute("count", new Integer(this.count));}@Overridepublic void sessionDestroyed(HttpSessionEvent se) {// TODO Auto-generated method stub//當(dāng)ession銷毀時(shí),count--count--;//將人數(shù)設(shè)置在ServletContext中sc.setAttribute("count", new Integer(this.count));}@Overridepublic void contextInitialized(ServletContextEvent sce) {// TODO Auto-generated method stub//Tomcat啟動(dòng)時(shí)獲取ServletContext,并設(shè)置一個(gè)登陸人數(shù)(初值為0);this.sc = sce.getServletContext();this.sc.setAttribute("count", new Integer(this.count));}@Overridepublic void contextDestroyed(ServletContextEvent sce) {// TODO Auto-generated method stubsc = null;} }?
LoginServlet:
import java.io.IOException; import java.io.PrintWriter;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;import com.util.*;// http://localhost:8080/TestServlet/Filter/Login public class LoginServlet extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {PrintWriter out = response.getWriter();String username = request.getParameter("username");HttpSession session = request.getSession();//獲取ServletContextServletContext sc = this.getServletContext();HttpPageUtil.printHtmlPage(out, true);//從ServletContext中獲取人數(shù)。out.println("歡迎" + username + "當(dāng)前在線人數(shù)" + ((Integer)sc.getAttribute("count")).intValue());HttpPageUtil.printHtmlPage(out, false);}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub doGet(request, response);} }?
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Login</title> </head> <body><!--在.../Page/下重定向 不加 /的相對(duì)路徑 --><!-- http://localhost:8080/TestServlet/Page/Filter/Login --><form name = f1 action ="/TestServlet/Filter/Login" method = "post">username:<input type = "text" name = "username" value = "${un}"></input><br>password:<input type = "password" name = "password" value = "${pw}"></input><br><!-- 記住密碼 :<input type = "radio" name = "SavePassword" value = "1"><br> --><input type = "submit" value = "登錄"></form> </body> </html>每登錄一個(gè)用戶都會(huì)為其創(chuàng)建一個(gè)Session,這里測(cè)試時(shí)最好用不同的瀏覽器。
如果是一個(gè)瀏覽器,此例中多次登錄會(huì)被認(rèn)為是一個(gè)session,不會(huì)觸發(fā)Session創(chuàng)建監(jiān)聽。
?
轉(zhuǎn)載于:https://www.cnblogs.com/huang-changfan/p/10320746.html
總結(jié)
以上是生活随笔為你收集整理的1.8(学习笔记)监听器(Listener)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 妈妈对女儿说的暖心句239个
- 下一篇: 大户型住宅使用Mesh组网技术Wi