學習大數據——Listener監視器的介紹和簡單使用

Listener監視器

  1. Listener用於監聽JavaWeb程序中的事件。
  2. 例如:ServletContext、HttpSession、ServletRequest的創建、修改和刪除。
  3. 監聽器的類型分爲
    ① 生命週期
    ② 數據綁定
    Listener
    使用實例:

顯示頁面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<center>
	<h1>歡迎 <span style="color:blue">${sessionScope.user.username }</span> 登錄,當前在線人數<span style="color:red">${applicationScope.count }</span><a href="${pageContext.request.contextPath }/LogoutServlet">註銷</a></h1>
	<c:if test="${empty requestScope.users }">
		<h1>沒有任何用戶!</h1>
	</c:if>
	<c:if test="${not empty requestScope.users }">
		<h1>用戶列表</h1>
		<table border="1" cellpadding="10" cellspacing="0">
			<tr>
				<th>ID</th>
				<th>Username</th>
				<th>Password</th>
				<th>Email</th>
				<th colspan="2">Operate</th>
			</tr>
			<c:forEach items="${requestScope.users }" var="user">
			<tr>
				<td>${user.id }</td>
				<td>${user.username }</td>
				<td>${user.password }</td>
				<td>${user.email }</td>
				<td><a href="#">Edit</a></td>
				<td><a href="#">Delete</a></td>
			</tr>
			</c:forEach>
		</table>
	</c:if>
	</center>
</body>
</html>

LoginServlet登錄Servlet:

/**
 * 處理用戶登錄的Servlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		//獲取用戶名和密碼
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		//創建UserDao對象
		UserDao userDao = new UserDaoImpl();
		//調用UserDao中UserDao中驗證用戶名和密碼方法
		User user = userDao.checkUsernameAndPassword(username, password);
		if(user != null) {
			//用戶名和密碼正確,重定向登錄成功頁面			
			//response.sendRedirect(request.getContextPath()+"/page/login_success.jsp");
			HttpSession session = request.getSession();
			//將用戶信息保存到session域中
			session.setAttribute("user", user);
			//重定向到查詢所有用戶的請求
			response.sendRedirect(request.getContextPath()+"/GetUsersServlet");
		}else {
			//用戶名或密碼不正確,設置一個錯誤信息並放到request域中
			request.setAttribute("msg", "用戶名或密碼不正確!");
			//轉發到等錄頁面
			//獲取轉發器
			RequestDispatcher requestDispatcher = request.getRequestDispatcher("/page/login.jsp");
			//進行請求的轉發
			requestDispatcher.forward(request, response);
		}
	}

LogoutServlet註銷的Servlet:

/**
 * 註銷的Servlet
 */
public class LogoutServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//獲取Session對象
		HttpSession session = request.getSession();
		//使Session對象失效
		session.invalidate();
		//重定向到首頁
		response.sendRedirect(request.getContextPath() +"/index.jsp");
	}

用戶實體:

public class User implements Serializable, HttpSessionBindingListener{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Integer id;
	private String username;
	private String password;
	private String email;
	
	public User(Integer id, String username, String password, String email) {
		super();
		this.id = id;
		this.username = username;
		this.password = password;
		this.email = email;
	}
	public User() {
		super();
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	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 String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + "]";
	}
	//向Session域中添加User對象是調用
	@Override
	public void valueBound(HttpSessionBindingEvent event) {
		//獲取Session對象
		HttpSession session = event.getSession();
		//獲取ServletContext對象
		ServletContext application = session.getServletContext();
		//從application域中獲取當前在線人數
		Integer count = (Integer) application.getAttribute("count");
		if(count == null ) {
			//證明之前還沒有人上線,此時需要向application域中設置在線人數爲1
			application.setAttribute("count", 1);
		}else {
			//證明之前已經有人在線,此時需要將之前的在線人數加1並再次放到application域中
			application.setAttribute("count", count+1);
		}
	}
	//User對象從Session域中移除時調用
	@Override
	public void valueUnbound(HttpSessionBindingEvent event) {
		HttpSessionBindingListener.super.valueUnbound(event);
		//獲取Session對象
		HttpSession session = event.getSession();
		//獲取ServletContext對象
		ServletContext application = session.getServletContext();
		//從application域中獲取當前在線人數
		Integer count = (Integer) application.getAttribute("count");
		application.setAttribute("count", count-1);
	}
}

說明:

  1. 當用戶登錄時,User對象被創建,而將User對象加入到Session域中時valueBound方法被調用,使在線人數增加,從而可以統計當前的在線人數。
  2. 當用戶退出時,User對象從Session中被移除,valueUnbound方法被調用,使在線人數減少,從而可以統計當前準確的在線人數。
發佈了41 篇原創文章 · 獲贊 7 · 訪問量 797
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章