1. 程式人生 > >java技術學習路徑之:Javaweb監聽器總結(應用場景、方法、配置)

java技術學習路徑之:Javaweb監聽器總結(應用場景、方法、配置)

配置 包名 quest ner web.xml 監聽器接口 tty 數據 XML

JavaWeb中,監聽器是一種組件,能夠監聽項目的啟動和停止,用戶會話的創建和銷毀,以及各種組件的添加、更新和刪除,能夠通過監聽對象的狀態改變,自動做出反應執行響應代碼。

應用場景:

啟動網站後進行初始化、檢測用戶的數量等。

常用的監聽器接口:

ServletContextListener 監聽項目的啟動和停止

方法:

contextInitialized 項目加載完成

contextDestroyed 項目停止

HttpSessionListener 監聽用戶會話的創建和銷毀

sessionCreated 每一個用戶第一次訪問時調用

sessionDestroyed 每個用戶退出系統後調用

監聽器的配置:

方式1 web.xml

<listener>

<listener-class>包名+類名</listener-class>

</listener>

方式2 註解

@WebListener

案例:監聽網站的啟動

/**

?* 項目的監聽器

?* @author chenheng

?*

?*/

@WebListener

public class WebApplicationListener implements ServletContextListener{

?

//項目啟動

@Override

public void contextInitialized(ServletContextEvent sce) {

System.out.println("項目啟動了!!!!");

//保存一些數據到項目中

sce.getServletContext().setAttribute("money", 999999);

}

?

//項目停止

@Override

public void contextDestroyed(ServletContextEvent sce) {

System.out.println("項目停止了!!!!!");

}

}

案例:監聽網站的用戶數

/**

?* 會話監聽器

?* @author chenheng

?*

?*/

@WebListener

public class UserListener implements HttpSessionListener{

?

//用戶會話創建

@Override

public void sessionCreated(HttpSessionEvent se) {

//把用戶的數量保存到ServletContext(application)中

ServletContext application = se.getSession().getServletContext();

//獲得用戶的總數

Object count = application.getAttribute("count");

if(count == null){

//如果是第一個用戶,沒有總數,添加總數

application.setAttribute("count", 1);

System.out.println("第一個用戶");

}else{

//如果不是第一個,就用戶數量加1

application.setAttribute("count", (int)count + 1);

System.out.println("新用戶來了");

}

}

?

//用戶會話銷毀

@Override

public void sessionDestroyed(HttpSessionEvent se) {

ServletContext application = se.getSession().getServletContext();

Object count = application.getAttribute("count");

if(count != null && (int)count > 0){

application.setAttribute("count", (int)count - 1);

System.out.println("用戶走了");

}

}

}

?

/**

?* 關閉Session的Servlet

?*/

@WebServlet("/close.do")

public class CloseSessionServlet extends HttpServlet{

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//關閉Session

req.getSession().invalidate();

}

}

?

?

JSP頁面:

<%@ page language="java" contentType="text/html; charset=UTF-8"

????pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>測試</title>

</head>

<body>

當前網站在線人數:${count}<br>

<a href="javascript:location.href=‘close.do‘;">退出</a>

</body>

</html>

java技術學習路徑之:Javaweb監聽器總結(應用場景、方法、配置)