JavaWeb(六)——監聽器與過濾器

第六章:監聽器與過濾器

第1節:監聽器


知識點1:監聽器的作用

1.定義

​ 當事件發生的時候,需要進行一些處理,就可以使用監聽器處理.

2.作用

​ 監聽器監聽的是事件,當事件發生的時候,監聽器進行相應的處理.
在這裏插入圖片描述


知識點2:監聽器相關API

1.事件類

​ 事件類定義了事件類型

​ Servlet API定義了6種事件類型:

(1)上下文相關事件
①ServletContextEvent:上下文事件

1)觸發時機

​ 當上下文對象發生改變,比如:創建上下文,銷燬上下文的時候,會觸發上下文事件

2)創建上下文

​ 服務器啓動的時候會觸發創建上下文事件

3)銷燬上下文

​ 服務器停止的時候會觸發銷燬上下文事件

②ServletContextAttributeEvent:上下文屬性事件

1)觸發時機

​ 當上下文的屬性發生改變,如添加,刪除,覆蓋上下文的屬性時,會觸發上下文屬性事件

2)添加上下文的屬性

​ 調用servletContext.setAttribute(name,value)方法的時候會觸發上下文屬性事件

3)刪除上下文屬性

​ 調用servletContext.removeAttribute(name)方法的時候會觸發上下文屬性事件

4)覆蓋上下文屬性

​ 調用servletContext.setAttribute(name,value)方法的時候會觸發上下文屬性事件

(2)請求相關事件
①ServletRequestEvent:請求事件

1)觸發時機

​ 請求對象發生改變的時候,創建請求對象,銷燬請求對象的時候會觸發請求事件.

2)創建請求對象

​ 當客戶端瀏覽器請求一個servlet的時候就會創建請求對象,就會觸發請求事件

3)銷燬請求對象

​ 當服務器將響應發送給客戶端瀏覽器以後請求對象被銷燬,也會觸發請求事件

②ServletReqeustAttributeEvent:請求屬性事件

1)觸發時機

​ 當請求屬性發生改變,如:添加,刪除,覆蓋請求的屬性,會觸發請求屬性事件

2)添加請求屬性

​ 調用request.setAttribute(name,value)方法時會觸發請求屬性事件

3)刪除請求屬性

​ 調用request.removeAttribute(name)方法時會觸發請求屬性事件

4)覆蓋請求屬性

​ 調用request.setAttribute(name,value)方法時會觸發請求屬性事件

(3)會話相關事件
①HttpSessionEven會話事件

​ 會話對象發生改變,創建會話對象,銷燬會話對象,活化或者鈍化會話對象,會觸發會話事件.

1)創建會話對象

​ 調用request.getSession()方法或者request.getSession(true)創建session會話對象,會觸發會話事件

2)銷燬會話對象

​ 默認30分鐘.銷燬會話對象,會觸發會話事件

​ web.xml配置 50分鐘 銷燬會話對象,會觸發會話事件

​ 調用session.invalidate()方法銷燬會話對象,會觸發會話事件

​ 調用session.setMaxInactiveInterval(多少秒)方法銷燬會話對象,會觸發會話事件

3)活化會話對象

​ session會話對象從磁盤取出反序列化到內存形成session會話對象,活化會話對象,會觸發會話事件

4)鈍化會話對象

​ session會話對象序列化到磁盤,鈍化會話對象,會觸發會話事件

②HttpSessionBindingEvent會話綁定事件

1)觸發時機

​ 當會話屬性發生改變,如:添加,刪除,覆蓋會話的屬性,會觸發會話綁定事件

2)添加會話屬性

​ 調用session.setAttribute(name,value)方法時會觸發請求綁定事件

3)刪除會話屬性

​ 調用session.removeAttribute(name)方法時會觸發請求綁定事件

4)覆蓋會話屬性

​ 調用session.setAttribute(name,value)方法時會觸發請求綁定事件

2.監聽器接口

​ 監聽器接口定義了監聽事件的方法

​ Servlet API中定義了8種監聽器接口,用來監聽不同的事件類型

(1)上下文相關的監聽器

​ ①上下文監聽器ServletContextListener,監聽上下文事件ServletContextEvent

​ ②上下文屬性監聽器ServletContextAttributeListener,監聽ServletContextAttributeListener上下文屬性事件

(2)請求相關的監聽器

​ ①請求監聽器ServletRequestListener

​ ②請求屬性監聽器ServletRequestAttributeListener

(3)會話相關的監聽器

​ 會話監聽器HttpSessionListener

​ 會話活化監聽器HttpSessionActivationListener

​ 會話屬性監聽器HttpSessionAttributeListener

​ 會話綁定監聽器 HttpSessionBindingListener


知識點3:監聽器的開發與配置

​ 寫一個類實現XXXListener接口

​ 重寫接口中的方法,實現監聽的功能

​ web.xml配置listener

1、創建MyContextListner

2、重寫接口中的方法,實現監聽的功能
package com.tjetc.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * Application Lifecycle Listener implementation class MyContextLisener
 *
 */
public class MyContextLisener implements ServletContextListener {

    /**
     * Default constructor. 
     */
    public MyContextLisener() {
        // TODO Auto-generated constructor stub
    }

	/**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent sce)  { 
         // TODO Auto-generated method stub
    	System.out.println("MyContextLisener.contextDestroyed()..."+sce.getServletContext());
    }

	/**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent sce)  { 
         System.out.println("MyContextLisener.contextInitialized()..."+sce.getServletContext());
    }
}

輸出:

​ 信息: 正在啓動 Servlet 引擎:[Apache Tomcat/9.0.34]

​ MyContextLisener.contextInitialized()…


知識點4:上下文相關監聽器

①創建MyContextAttributeListener,實現ServletContextAttributeListener接口
②重寫接口的方法
③寫MyContextAttributeServlet,向上下文添加屬性,覆蓋屬性,刪除屬性
④運行MyContextAttributeServlet
package com.tjetc.listener;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;

/**
 * Application Lifecycle Listener implementation class MyContextAttributeLisener
 *
 */
public class MyContextAttributeLisener implements ServletContextAttributeListener {

    /**
     * Default constructor. 
     */
    public MyContextAttributeLisener() {
        // TODO Auto-generated constructor stub
    }

	/**
     * @see ServletContextAttributeListener#attributeAdded(ServletContextAttributeEvent)
     */
    public void attributeAdded(ServletContextAttributeEvent scae)  { 
         System.out.println("MyContextAttributeLisener.attributeAdded():"+scae.getName()+"="+scae.getValue());
    }

	/**
     * @see ServletContextAttributeListener#attributeRemoved(ServletContextAttributeEvent)
     */
    public void attributeRemoved(ServletContextAttributeEvent scae)  { 
         // TODO Auto-generated method stub
    	System.out.println("MyContextAttributeLisener.attributeRemoved():"+scae.getName()+"="+scae.getValue());
    }

	/**
     * @see ServletContextAttributeListener#attributeReplaced(ServletContextAttributeEvent)
     */
    public void attributeReplaced(ServletContextAttributeEvent scae)  { 
         // TODO Auto-generated method stub
    	System.out.println("MyContextAttributeLisener.attributeReplaced():"+scae.getName()+"="+scae.getValue());
    }
	
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//得到上下文對象
		ServletContext servletContext = getServletContext();
		//向上下文中添加屬性
		servletContext.setAttribute("name", "zs");
		//覆蓋屬性
		servletContext.setAttribute("name", "lisi");
		//刪除屬性
		servletContext.removeAttribute("name");
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

輸出

MyContextAttributeLisener.attributeAdded():name=zs MyContextAttributeLisener.attributeReplaced():name=zs MyContextAttributeLisener.attributeRemoved():name=lisi


知識點5:會話相關監聽器

HttpSessionListener:會話監聽器,當會話對象被創建後或銷燬前需要一些自定義處理時,可以用此監聽器監聽;

HttpSessionActivationListener:會話活化監聽器,會話對象存在於服務器端,只要沒有失效,服務器就得分配空間給其使用;爲了能夠提高使用效率,服務器有內在的活化鈍化機制,可以將暫時不使用的會話對象鈍化到外存,需要使用時再活化到內存。當活化後或鈍化前需要一些自定義處理時,可以使用該監聽器;

HttpSessionAttributeListener:會話屬性監聽器,當會話中的屬性被添加、刪除、替換時,要進行一些自定義處理時,可以使用該監聽器,使用時可以用事件對象獲取屬性的名字等信息。

HttpSessionBindingListener:會話綁定監聽器,當類實現了HttpSessionBindingListener接口後,該類對象綁定或解除綁定到會話時,就會被該監聽器監聽。綁定指的是調用setAttribute方法,解除綁定指的是調用removeAttribute方法,或者會話超時、會話失效等。


第2節:過濾器


知識點1:過濾器的作用

​ 把通用的、相同的處理代碼用過濾器實現,可以共享,然後在web.xml中將過濾器配置給相關的資源使用即可

在這裏插入圖片描述

知識點2:過濾器的開發方法

1.寫一個類實現Filter接口

2.重寫Filter接口的三個方法
在這裏插入圖片描述

知識點3:過濾器的各個方法執行順序

1.構造方法

2.init(filterConfig)初始化方法

3.doFilter()方法

4.destroy()方法

package com.tjetc.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloServlet
 */
public class HelloServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @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);
	}

}

在這裏插入圖片描述


知識點4:FilterConfig接口方法

在這裏插入圖片描述

MyFilter的初始化方法:

public void init(FilterConfig fConfig) throws ServletException {
		System.out.println("MyFilter.init()方法:"+fConfig);
		String filterName = fConfig.getFilterName();
		System.out.println(filterName);
		//得到初始化參數的值
		String name = fConfig.getInitParameter("name");
		System.out.println(name);
		//得到所有初始化參數的名字
		Enumeration<String> names = fConfig.getInitParameterNames();
		while (names.hasMoreElements()) {
			String string = (String) names.nextElement();
			System.out.println(string);
		} 
		//得到上下文對象
		ServletContext servletContext = fConfig.getServletContext();
		System.out.println(servletContext);
	}

在這裏插入圖片描述


知識點5:FilterChain接口的方法

在這裏插入圖片描述

知識點6:編碼過濾器

package com.tjetc.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * Servlet Filter implementation class CodeFilter
 */
public class CodeFilter implements Filter {
	FilterConfig filterConfig;
    /**
     * Default constructor. 
     */
    public CodeFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		String encoding = filterConfig.getInitParameter("encoding");
		System.out.println(encoding);
		request.setCharacterEncoding(encoding);
		response.setCharacterEncoding(encoding);
		response.setContentType("text/html;charset="+encoding);
		// pass the request along the filter chain
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
		filterConfig=fConfig;
	}

}

輸出

​ UTF-8

​ 趙六

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章