日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Servlet 应用程序事件、监听器

發布時間:2023/12/9 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Servlet 应用程序事件、监听器 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

  Web容器管理Servlet/JSP相關的生命周期,若對HttpServletRequest對象、HttpSession對象、ServletContxt對象在生成、銷毀或相關屬性設置發生的時機點有興趣,可以實現對應的監聽器(Listener)。

?

一、ServletContext事件、監聽器

?

??? 與ServletContext相關的監聽器有兩個,ServletContextListener、ServletContextAttributeListener

?

1、ServletContextListener

?

??? 它是生命周期監聽器,如果想要知道何時web應用程序已經初始化或者即將結束銷毀,可以實現該監聽器。

?

??? 例如,可以實現ServletContextListener,在此應用程序初始過程中,準備好數據庫連接線對象、讀取應用程序設置等動作,如放置使用頭像的目錄信息,就不適合將目錄名稱寫死,這時候可以這么做:

1 package cc.openhome; 2 import javax.servlet.*; 3 @WebListener //使用@weblistener標注 4 public class ContextParameterReader implements ServletContextListener{ 5 public void contextInitialized(ServletContextEvent e){ 6 ServletContext context = sce.getServletContext();//取得ServletContext 7 String avatars = context.getInitParameter("AVATAR");//取得初始參數 8 context.setAttribute("avatars",avatars);//設置ServletContext屬性 9 } 10 public void contextDestroyed(ServletContextEvent sce){} 11 }

  整個web應用程序生命周期,Servlet共享的資料可以設置為ServletContext屬性。這些屬性數據會一直存在于web應用程序中。可以通過setAttribute()方法設置對象為ServletContext屬性,之后可通過ServletContext的getAttribute()方法取出該屬性。如果移除屬性,用removeAttribute()。

1 package ServletAPI; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.annotation.WebInitParam; 8 import javax.servlet.annotation.WebServlet; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 13 /** 14 * Servlet implementation class Avatar 15 */ 16 @WebServlet( 17 urlPatterns = { "/avatar.view" }, 18 initParams = { 19 @WebInitParam(name = "AVATAR_DIR", value = "/image")//根目錄WebContent內部 20 }) 21 public class Avatar extends HttpServlet { 22 private static final long serialVersionUID = 1L; 23 private String AVATAR_DIR; 24 /** 25 * @see HttpServlet#HttpServlet() 26 */ 27 public Avatar() { 28 super(); 29 // TODO Auto-generated constructor stub 30 } 31 public void init() throws ServletException{ 32 //AVATAR_DIR=getInitParameter("AVATAR_DIR"); 33 AVATAR_DIR=(String) getServletContext().getAttribute("avatars"); 34 } 35 36 37 /** 38 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 39 */ 40 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 41 // TODO Auto-generated method stub 42 response.setContentType("text/html;charset=UTF-8"); 43 PrintWriter out=response.getWriter(); 44 out.println("<!DOCTYPE html>"); 45 out.println("<html>"); 46 out.println("<head>"); 47 out.println("<meta content='text/html; charset=UTF-8' http-equiv='content-type'>"); 48 out.println("<title>頭像顯示</title>"); 49 out.println("</head>"); 50 out.println("<body>"); 51 for(String avatar:getServletContext().getResourcePaths(AVATAR_DIR)){//取得頭像路徑 52 avatar=avatar.replaceFirst("/", ""); 53 out.println("<img src='"+avatar+"'>"); 54 } 55 out.println("</body>"); 56 out.println("</html>"); 57 out.close(); 58 } 59 60 /** 61 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 62 */ 63 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 64 // TODO Auto-generated method stub 65 } 66 67 } avatar.java

2、ServletContextAttributeListener

??? 它是監聽屬性改變的監聽器,如果想要對象被設置、移除或替換ServletContext屬性,也可以收到通知以進行一些操作,可以實現該監聽器。

??? 當在ServletContext中添加屬性、移除或者替換屬性時,對應的attributeAdded()、attributeRemoved()、attributeReplaced()方法就會被調用。

二、HttpSession事件、監聽器

??? 與HttpSession相關的有四個監聽器:HttpSessionListener、HttpSessionAttributeListener、HttpSessionBindingListener與HttpSessionActivationListener.

1、HttpSessionListener

??? 它是生命周期監聽器,如果想要在HttpSession對象創建或者結束時,做些相對應動作,可以實現該監聽。

??? 在HttpSession對象初始化或結束之前,會分別調用sessionCreated()、sessionDestroyed()方法,

可以通過傳入的HttpSessionEvent,使用getSession()取得HttpSession,以針對會話對象做出相應操作。例如:除非用戶注銷,否則登錄后的用戶在另個瀏覽器上登錄會顯示登錄失敗。

??? 如果用戶不小心再注銷前關閉了瀏覽器,那么數據庫中代表登錄與否的字段就不會被重置。為此,可是實現HttpSessionListener,由于HttpSession有存活期限,當容器銷毀某個HttpSession時,就會調用sessionDestroyed(),就可以再當中判斷要重置哪個用戶的數據庫中代表登錄與否的字段。

??? 例1:顯示目前已經在線人數的統計。

1 package ServletAPI; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import javax.servlet.ServletException; 6 import javax.servlet.annotation.WebServlet; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 import javax.servlet.http.HttpSession; 11 12 /** 13 * Servlet implementation class Welcome 14 */ 15 @WebServlet("/welcome.view") 16 public class Welcome extends HttpServlet { 17 private static final long serialVersionUID = 1L; 18 19 /** 20 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 21 */ 22 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 23 // TODO Auto-generated method stub 24 response.setContentType("text/html;charset=UTF-8"); 25 PrintWriter out=response.getWriter(); 26 HttpSession session=request.getSession(true); 27 out.println("<html>"); 28 out.println("<head>"); 29 out.println("<title>歡迎</title>"); 30 out.println("</head>"); 31 out.println("<body>"); 32 out.println("<h1>目前在線人數"+OnlineUserCounter.getCounter()+"人</h1>");//獲取在線人數 33 if(session!=null){ 34 String user=(String) session.getAttribute("user"); 35 out.println("<h1>歡迎:"+user+"</h1>"); 36 out.println("<a href='logout.do'>注銷</a>"); 37 } 38 out.println("</body>"); 39 out.println("</html>"); 40 } 41 42 } Welcome.java 1 package ServletAPI; 2 3 import javax.servlet.annotation.WebListener; 4 5 import javax.servlet.http.HttpSessionEvent; 6 import javax.servlet.http.HttpSessionListener; 7 8 /** 9 * Application Lifecycle Listener implementation class OnlineUserCounter 10 * 11 */ 12 @WebListener() 13 public class OnlineUserCounter implements HttpSessionListener { 14 private static int counter; 15 16 public static int getCounter(){ 17 return counter; 18 } 19 20 /** 21 * @see HttpSessionListener#sessionCreated(HttpSessionEvent) 22 */ 23 public void sessionCreated(HttpSessionEvent se) { 24 // TODO Auto-generated method stub 25 OnlineUserCounter.counter++; 26 } 27 28 /** 29 * @see HttpSessionListener#sessionDestroyed(HttpSessionEvent) 30 */ 31 public void sessionDestroyed(HttpSessionEvent se) { 32 // TODO Auto-generated method stub 33 OnlineUserCounter.counter--; 34 } 35 36 } OnlineUserCounter.java 1 package ServletAPI; 2 3 import java.io.IOException; 4 import java.util.HashMap; 5 import java.util.Map; 6 7 import javax.print.attribute.standard.PagesPerMinute; 8 import javax.servlet.ServletException; 9 import javax.servlet.annotation.WebServlet; 10 import javax.servlet.http.HttpServlet; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 14 import org.apache.catalina.User; 15 16 /** 17 * Servlet implementation class loginlistener 18 */ 19 @WebServlet("/listener.view") 20 public class loginlistener extends HttpServlet { 21 private static final long serialVersionUID = 1L; 22 private Map<String, String> users; 23 /** 24 * @see HttpServlet#HttpServlet() 25 */ 26 public loginlistener() { 27 //super(); 28 users=new HashMap<String, String>(); 29 users.put("nihao", "nihaonihao"); 30 users.put("momor", "123456789"); 31 users.put("hamimi", "123456789"); 32 // TODO Auto-generated constructor stub 33 } 34 35 /** 36 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 37 */ 38 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 39 // TODO Auto-generated method stub 40 String name=request.getParameter("user"); 41 String passwd=request.getParameter("passwd"); 42 String page="listenerlogin.html"; 43 if(users.containsKey(name) && users.get(name).equals(passwd)){ 44 User user=(User) new ServletAPI.User(name); 45 request.getSession().setAttribute("user", user); 46 page="welcome.view"; 47 } 48 response.sendRedirect(page); 49 } 50 51 } login.java

  運行結果

2、HttpSessionAttributeListener

??? 它是屬性改變監聽器,用法同ServletContextAttributeListener一樣。

3、HttpSessionBindingListener

??? 它是對象綁定監聽器,如果有個即將加HttpSessionBindingListener入HttpSession的屬性對象,希望在設置給HttpSession成為屬性或從HttpSession中刪除時,可以收到HttpSession的通知,可以讓該對象實現該監聽器。

??? 當實現此接口的屬性對象被加入HttpSession或沖中移除,就會調用valueBound()與valueUnbound()方法,并傳入HttpSessionBindingEvent對象,可以通過該對象的getSession()取得HttpSession對象。

4、HttpSessionActivationListener

??? 對象遷移監聽器,幾乎不會用到。

三、HttpServletRequest事件、監聽器

??? 有三個相關的監聽器:ServletRequestListener、ServletRequestAttributeListener、AsyncListener(這個在異步處理時會介紹到)。

?

轉載于:https://www.cnblogs.com/liuzhongfeng/p/6107090.html

總結

以上是生活随笔為你收集整理的Servlet 应用程序事件、监听器的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。