拦截器,过滤器,监听器原理
過濾器
創(chuàng)建一個Filter 只需兩個步驟:?
(1)創(chuàng)建Filter 處理類:?
(2)在web.xml 文件中配置Filter 。?
創(chuàng)建Filter 必須實現(xiàn)javax.servlet.Filter 接口,在該接口中定義了三個方法。?
? void init(FilterConfig config): 用于完成Filter 的初始化。?
? void destroy(): 用于Filter 銷毀前,完成某些資源的回收。?
? void doFilter(ServletRequest request, ServletResponse response,FilterChain chain): 實現(xiàn)過濾功能,該方法就是對每個請求及響應(yīng)增加的額外處理。?
過濾器Filter也具有生命周期:init()->doFilter()->destroy(),由部署文件中的filter元素驅(qū)動。在servlet2.4中,過濾器同樣可以用于請求分派器,但須在web.xml中聲明,<dispatcher>INCLUDE或FORWARD或REQUEST或ERROR</dispatcher>該元素位于filter-mapping中。?
一、理解Struts2攔截器
1. Struts2攔截器是在訪問某個Action或Action的某個方法,字段之前或之后實施攔截,并且Struts2攔截器是可插拔的,攔截器是AOP的一種實現(xiàn).
2. 攔截器棧(Interceptor Stack)。Struts2攔截器棧就是將攔截器按一定的順序聯(lián)結(jié)成一條鏈。在訪問被攔截的方法或字段時,Struts2攔截器鏈中的攔截器就會按其之前定義的順序被調(diào)用。
二、實現(xiàn)Struts2攔截器原理
Struts2攔截器的實現(xiàn)原理相對簡單,當(dāng)請求struts2的action時,Struts 2會查找配置文件,并根據(jù)其配置實例化相對的??? 攔截器對象,然后串成一個列表,最后一個一個地調(diào)用列表中的攔截器
三、定義Struts2攔截器。
Struts2規(guī)定用戶自定義攔截器必須實現(xiàn)com.opensymphony.xwork2.interceptor.Interceptor接口。該接口聲明了3個方法,
| void init(); void destroy(); String intercept(ActionInvocation ? invocation) throws Exception; |
其中,init和destroy方法會在程序開始和結(jié)束時各執(zhí)行一遍,不管使用了該攔截器與否,只要在struts.xml中聲明了該Struts2攔截器就會被執(zhí)行。
intercept方法就是攔截的主體了,每次攔截器生效時都會執(zhí)行其中的邏輯。
不過,struts中又提供了幾個抽象類來簡化這一步驟。
| public abstract class AbstractInterceptor ? implements Interceptor; public abstract class ? MethodFilterInterceptor extends AbstractInterceptor; |
都是模板方法實現(xiàn)的。
其中AbstractInterceptor提供了init()和destroy()的空實現(xiàn),使用時只需要覆蓋intercept()方法;
而MethodFilterInterceptor則提供了includeMethods和excludeMethods兩個屬性,用來過濾執(zhí)行該過濾器的action的方法。可以通過param來加入或者排除需要過濾的方法。
一般來說,攔截器的寫法都差不多。看下面的示例:
| package interceptor; import ? com.opensymphony.xwork2.ActionInvocation; import ? com.opensymphony.xwork2.interceptor.Interceptor; public class MyInterceptor implements ? Interceptor { public void destroy() { // TODO Auto-generated method stub } public void init() { // TODO Auto-generated method stub } public String intercept(ActionInvocation ? invocation) throws Exception { System.out.println("Action執(zhí)行前插入 代碼");????? ? //執(zhí)行目標(biāo)方法 (調(diào)用下一個攔截器, 或執(zhí)行Action)??? ? final String res = ? invocation.invoke();??? System.out.println("Action執(zhí)行后插入 代碼");??? return res;??? } } |
四、配置Struts2攔截器
Struts2攔截器需要在struts.xml中聲明,如下struts.xml配置文件
| <?xml version="1.0" ? encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD ? Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant ? name="struts.objectFactory" value="spring" /> ? <package name="default" extends="struts-default"> <interceptors> <interceptor ? name="MyInterceptor" ? class="interceptor.MyInterceptor"></interceptor> <interceptor-stack ? name="myInterceptorStack"> <interceptor-ref ? name="MyInterceptor"/> <interceptor-ref ? name="defaultStack"/> </interceptor-stack> </interceptors> <action name="loginAction" ? class="loginAction"> <result ? name="fail">/index.jsp </result> <result ? name="success">/success.jsp</result> <interceptor-ref ? name="myInterceptorStack"></interceptor-ref> </action> </package> </struts> |
?
?
?
攔截器與過濾器的區(qū)別 :
?
?
?? ?監(jiān)聽器概述 ??
????1.Listener是Servlet的監(jiān)聽器? ??
??2.可以監(jiān)聽客戶端的請求、服務(wù)端的操作等。 ??
??3.通過監(jiān)聽器,可以自動激發(fā)一些操作,如監(jiān)聽在線用戶數(shù)量,當(dāng)增加一個HttpSession時,給在線人數(shù)加1。 ??
??4.編寫監(jiān)聽器需要實現(xiàn)相應(yīng)的接口 ??
??5.編寫完成后在web.xml文件中配置一下,就可以起作用了 ??
??6.可以在不修改現(xiàn)有系統(tǒng)基礎(chǔ)上,增加web應(yīng)用程序生命周期事件的跟蹤 ??
??
??3.HttpSessionListener ??常用接口
??監(jiān)聽HttpSession的操作。當(dāng)創(chuàng)建一個Session時,激發(fā)session?Created(SessionEvent?se)方法;當(dāng)銷毀一個Session時,激發(fā)sessionDestroyed?(HttpSessionEvent?se)方法。 ??
??4.HttpSessionAttributeListener ??
??監(jiān)聽HttpSession中的屬性的操作。當(dāng)在Session增加一個屬性時,激發(fā)attributeAdded(HttpSessionBindingEvent?se)?方法;當(dāng)在Session刪除一個屬性時,激發(fā)attributeRemoved(HttpSessionBindingEvent?se)方法;當(dāng)在Session屬性被重新設(shè)置時,激發(fā)attributeReplaced(HttpSessionBindingEvent?se)?方法。 ??
??
使用范例: ??
由監(jiān)聽器管理共享數(shù)據(jù)庫連接 ??
??
??生命周期事件的一個實際應(yīng)用由context監(jiān)聽器管理共享數(shù)據(jù)庫連接。在web.xml中如下定義監(jiān)聽器: ??
<listener> ??
????<listener-class>XXX.MyConnectionManager</listener-class> ??
</listener>??server創(chuàng)建監(jiān)聽器的實例,接受事件并自動判斷實現(xiàn)監(jiān)聽器接口的類型。要記住的是由于監(jiān)聽器是配置在部署描述符web.xml中,所以不需要改變?nèi)魏未a就可以添加新的監(jiān)聽器。 ??
??
public?class?MyConnectionManager?implements?ServletContextListener{?? ??
??public?void?contextInitialized(ServletContextEvent?e)?{? ??
????????Connection?con?=?//?create?connection? ??
????????e.getServletContext().setAttribute("con",?con);? ??
????}?? ??
???public?void?contextDestroyed(ServletContextEvent?e)?{? ??
????????Connection?con?=?(Connection)?e.getServletContext().getAttribute("con");? ??
????????try?{ ??
??????????con.close();? ??
????????}? ??
???????catch?(SQLException?ignored)?{?}?//?close?connection? ??
????}? ??
}?? ??
??監(jiān)聽器保證每新生成一個servlet?context都會有一個可用的數(shù)據(jù)庫連接,并且所有的連接對會在context關(guān)閉的時候隨之關(guān)閉。? ??
??
??
計算在線用戶數(shù)量的Linstener ??
(1) ??
Package?xxx;? ??
??
public?class?OnlineCounter?{?? ??
???private?static?long?online?=?0;????? ??
???public?static?long?getOnline(){ ??
??????return?online; ??
????} ??
????public?static?void?raise(){? ??
???????online++; ??
????} ??
????public?static?void?reduce(){? ??
???????online--;? ??
???} ??
}? ??
??
import?javax.servlet.http.HttpSessionEvent; ??
import?javax.servlet.http.HttpSessionListener; ??
??
public?class?OnlineCounterListener?implements?HttpSessionListener{ ??
????public?void?sessionCreated(HttpSessionEvent?hse)?{? ??
????????OnlineCounter.raise();?? ??
????}? ??
???public?void?sessionDestroyed(HttpSessionEvent?hse){?? ??
????????OnlineCounter.reduce(); ??
????}? ??
}? ??
??
在需要顯示在線人數(shù)的JSP中可是使用 ??
目前在線人數(shù): ??
<%@?page?import=“xxx.OnlineCounter"?%> ?
<%=OnlineCounter.getOnline()%> ?
?
退出會話(可以給用戶提供一個注銷按鈕): ?
<form?action="exit.jsp"?method=post>? ?
??<input?type=submit?value="exit">? ??
</form>? ??
??
exit.jsp:?<%session.invalidate()?;%>? ??
??
在web.xml中加入: ??
<listener>? ??
??<listener-class>servletlistener111111.SecondListener</listener-class>?</listener>
?
轉(zhuǎn)載于:https://www.cnblogs.com/shenweibk/articles/3031656.html
總結(jié)
以上是生活随笔為你收集整理的拦截器,过滤器,监听器原理的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 深度解析 TypeConverter
- 下一篇: OHCI,UHCI,EOHCI,XHCI