1.Servlet 過濾器是什么?
Servlet 過濾器是小型的 Web 組件,它們攔截請求和響應(yīng),以便查看、提取或以某種方式操作正在客戶機和服務(wù)器之間交換的數(shù)據(jù)。過濾器是通常封裝了一些功能的 Web 組件,這些功能雖然很重要,但是對于處理客戶機請求或發(fā)送響應(yīng)來說不是決定性的。典型的例子包括記錄關(guān)于請求和響應(yīng)的數(shù)據(jù)、處理安全協(xié)議、管理會話屬性,等等。過濾器提供一種面向?qū)ο蟮哪K化機制,用以將公共任務(wù)封裝到可插入的組件中,這些組件通過一個配置文件來聲明,并動態(tài)地處理。
Servlet 過濾器中結(jié)合了許多元素,從而使得過濾器成為獨特、強大和模塊化的 Web 組件。也就是說,Servlet 過濾器是:
聲明式的:過濾器通過 Web 部署描述符(web.xml)中的 XML 標(biāo)簽來聲明。這樣允許添加和刪除過濾器,而無需改動任何應(yīng)用程序代碼或 JSP 頁面。
動態(tài)的:過濾器在運行時由 Servlet 容器調(diào)用來攔截和處理請求和響應(yīng)。
靈活的:過濾器在 Web 處理環(huán)境中的應(yīng)用很廣泛,涵蓋諸如日志記錄和安全等許多最公共的輔助任務(wù)。過濾器還是靈活的,因為它們可用于對來自客戶機的直接調(diào)用執(zhí)行預(yù)處理和后期處理,以及處理在防火墻之后的 Web 組件之間調(diào)度的請求。最后,可以將過濾器鏈接起來以提供必需的功能。
模塊化的:通過把應(yīng)用程序處理邏輯封裝到單個類文件中,過濾器從而定義了可容易地從請求/響應(yīng)鏈中添加或刪除的模塊化單元。
可移植的:與 Java 平臺的其他許多方面一樣,Servlet 過濾器是跨平臺和跨容器可移植的,從而進(jìn)一步支持了 Servler 過濾器的模塊化和可重用本質(zhì)。
可重用的:歸功于過濾器實現(xiàn)類的模塊化設(shè)計,以及聲明式的過濾器配置方式,過濾器可以容易地跨越不同的項目和應(yīng)用程序使用。
透明的:在請求/響應(yīng)鏈中包括過濾器,這種設(shè)計是為了補充(而不是以任何方式替代)servlet 或 JSP 頁面提供的核心處理。因而,過濾器可以根據(jù)需要添加或刪除,而不會破壞 servlet 或 JSP 頁面。 2.Servlet 過濾器體系結(jié)構(gòu)
正如其名稱所暗示的, Servlet 過濾器用于攔截傳入的請求和/或傳出的響應(yīng),并監(jiān)視、修改或以某種方式處理正在通過的數(shù)據(jù)流。過濾器是自包含、模塊化的組件,可以將它們添加到請求/響應(yīng)鏈中,或者在無需影響應(yīng)用程序中其他 Web 組件的情況下刪除它們。過濾器僅只是改動請求和響應(yīng)的運行時處理,因而不應(yīng)該將它們直接嵌入 Web 應(yīng)用程序框架,除非是通過 Servlet API 中良好定義的標(biāo)準(zhǔn)接口來實現(xiàn)。
Web 資源可以配置為沒有過濾器與之關(guān)聯(lián)(這是默認(rèn)情況)、與單個過濾器關(guān)聯(lián)(這是典型情況),甚至是與一個過濾器鏈相關(guān)聯(lián)。那么過濾器究竟做什么呢? 像 servlet 一樣,它接受請求并響應(yīng)對象。然后過濾器會檢查請求對象,并決定將該請求轉(zhuǎn)發(fā)給鏈中的下一個組件,或者中止該請求并直接向客戶機發(fā)回一個響應(yīng)。如果請求被轉(zhuǎn)發(fā)了,它將被傳遞給鏈中的下一個資源(另一個過濾器、servlet 或 JSP 頁面)。在這個請求設(shè)法通過過濾器鏈并被服務(wù)器處理之后,一個響應(yīng)將以相反的順序通過該鏈發(fā)送回去。這樣就給每個過濾器都提供了根據(jù)需要處理響應(yīng)對象的機會。
當(dāng)過濾器在 Servlet 2.3 規(guī)范中首次引入時,它們只能過濾 Web 客戶機和客戶機所訪問的指定 Web 資源之間的內(nèi)容。如果該資源然后將請求調(diào)度給其他 Web 資源,那就不能向幕后委托的任何請求應(yīng)用過濾器。2.4 規(guī)范消除了這個限制。Servlet 過濾器現(xiàn)在可以應(yīng)用于 J2EE Web 環(huán)境中存在請求和響應(yīng)對象的任何地方。因此,Servlet 過濾器可以應(yīng)用在客戶機和 servlet 之間、servlet 和 servlet 或 JSP 頁面之間,以及所包括的每個 JSP 頁面之間。這才是我所稱的強大能力和靈活性!
3.編寫實現(xiàn)類的程序 過濾器 API 包含 3 個簡單的接口,它們整潔地嵌套在 javax.servlet 包中。那 3 個接口分別是 Filter 、 FilterChain 和 FilterConfig 。從編程的角度看,過濾器類將實現(xiàn) Filter 接口,然后使用這個過濾器類中的 FilterChain 和 FilterConfig 接口。該過濾器類的一個引用將傳遞給 FilterChain 對象,以允許過濾器把控制權(quán)傳遞給鏈中的下一個資源。 FilterConfig 對象將由容器提供給過濾器,以允許訪問該過濾器的初始化數(shù)據(jù)。
為了與我們的三步模式保持一致,過濾器必須運用三個方法,以便完全實現(xiàn) Filter 接口:
init() :這個方法在容器實例化過濾器時被調(diào)用,它主要設(shè)計用于使過濾器為處理做準(zhǔn)備。該方法接受一個 FilterConfig 類型的對象作為輸入。
doFilter() :與 servlet 擁有一個 service() 方法(這個方法又調(diào)用 doPost() 或者 doGet() )來處理請求一樣,過濾器擁有單個用于處理請求和響應(yīng)的方法―― doFilter() 。這個方法接受三個輸入?yún)?shù):一個 ServletRequest 、 response 和一個 FilterChain 對象。
destroy() :正如您想像的那樣,這個方法執(zhí)行任何清理操作,這些操作可能需要在自動垃圾收集之前進(jìn)行。 SessionFilter.java package net.pms.web.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; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper;
/** * @author jfish * @since 2006.1.12 */ public class SessionFilter implements Filter {
public static boolean isContains(String container, String[] regx) { boolean result = false;
for (int i = 0; i < regx.length; i++) { if (container.indexOf(regx) != -1) { return true; } } return result; }
public FilterConfig config;
public void setFilterConfig(FilterConfig config) { this.config = config; }
public FilterConfig getFilterConfig() { return config; }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpreq = (HttpServletRequest) request; HttpServletResponse httpres = (HttpServletResponse) response;
HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper( (HttpServletResponse) response); String logonStrings = config.getInitParameter("logonStrings"); String includeStrings = config.getInitParameter("includeStrings"); String redirectPath = httpreq.getContextPath() + config.getInitParameter("redirectPath"); String disabletestfilter = config.getInitParameter("disabletestfilter");
if (disabletestfilter.toUpperCase().equals("Y")) { chain.doFilter(request, response); return; } String[] logonList = logonStrings.split(";"); String[] includeList = includeStrings.split(";"); Object user = httpreq.getSession().getAttribute("userinfo"); if (user == null) { if (!this.isContains(httpreq.getRequestURI(), includeList)) { chain.doFilter(request, response); return; } if (this.isContains(httpreq.getRequestURI(), logonList)) { chain.doFilter(request, response); return; } wrapper.sendRedirect(redirectPath);
} else { chain.doFilter(request, response); } }
public void destroy() { this.config = null; }
public void init(FilterConfig filterConfig) throws ServletException { this.config = filterConfig; } } 4.配置 Servlet 過濾器 在web.xml中: <filter> <filter-name>SessionFilter</filter-name> <filter-class>net.pms.web.filter.SessionFilter</filter-class> <init-param> <param-name>logonStrings</param-name> <param-value>login.jsp</param-value> </init-param> <init-param> <param-name>includeStrings</param-name> <param-value>.jsp;.html</param-value> </init-param> <init-param> <param-name>redirectPath</param-name> <param-value>/login.jsp</param-value> </init-param> <init-param> <param-name>disabletestfilter</param-name> <param-value>N</param-value> </init-param> </filter> <filter-mapping> <filter-name>SessionFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 其中參數(shù)logonStrings,登陸頁面 includeStrings,過濾頁面參數(shù) redirectPath,沒有登陸轉(zhuǎn)向頁面 disabletestfilter,過濾器是否有效。 另附一字符集過濾類: package net.pms.web.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; /** * * @author jfish * @since 2006.1.12 * */ public class SetCharacterEncodingFilter implements Filter {
protected String encoding = null;
protected FilterConfig filterConfig = null;
protected boolean ignore = true;
public void destroy() {
this.encoding = null; this.filterConfig = null;
}
public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// Conditionally select and set the character encoding to be used if (ignore || (request.getCharacterEncoding() == null)) { String encoding = selectEncoding(request); if (encoding != null) request.setCharacterEncoding(encoding); }
// Pass control on to the next filter chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig; this.encoding = filterConfig.getInitParameter("encoding"); String value = filterConfig.getInitParameter("ignore"); if (value == null) this.ignore = true; else if (value.equalsIgnoreCase("true")) this.ignore = true; else if (value.equalsIgnoreCase("yes")) this.ignore = true; else this.ignore = false;
}
protected String selectEncoding(ServletRequest request) {
return (this.encoding);
}
} 在web.xml中配置如下: <filter> <filter-name>Set Character Encoding</filter-name> <filter-class>net.pms.web.filter.SetCharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>GBK</param-value> </init-param> </filter> <filter-mapping> <filter-name>Set Character Encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 不過,在spring中帶有此過濾器 在web.xml中配置如下: <filter> <filter-name>encodingFilter</filter-name> <filter-class> org.springframework.web.filter.CharacterEncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>GBK</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>*.html</url-pattern> </filter-mapping> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping>
|