轉servlet的高級應用

1:Filter(過濾器)

Filter是servlet2.3規範中新增加的,Filter並不是servlet,他不會對請求產生產生響應,但是他可以改變請求的內容,並且可以產生自己的相應。Filter是可重用的,當你在web應用中部署了一個Filter時,所有發送給這個應用的請求都要先經過這個Filter的處理。

Filter的用處:

1:訪問限制

2:日誌記錄

3:訪問資源的轉換(如xslt)

4:壓縮及加密

編寫Filter

一個filter 必須實現javax.servlet.Filter 接口,即實現下面的三個方法:
1:void init(FilterConfig config) throws ServletException
2:void destroy()
3:void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException

在init方法中你可以定義初始化一些Filter中用到的參數,或者從web.xml中讀取這些參數。

destroy方法是doFilter執行完畢後調用的方法
doFilter是編寫Filter的核心方法,在這個方法中編寫你的過濾代碼。

實例

假定我們要限定網絡地址處於202.117.96段的用戶訪問我們的應用,可以這樣編寫Filter:

import java.servlet.*;
public class MyFilter1 implements Filter {
protected FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig) throws ServletException {

this.filterConfig = filterConfig;

}

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {

String remoteIP=request.getRemoteAddr();
int n=remoteIP.lastIndexOf(".");
String s=remoteIP.substring(0,n);
if(s.equals("202.117.96")) {
PrintWriter out = response.getWriter();
out.println("<html><head></head><body>");
out.println("<h1>對不起,你沒有權利訪問這個應用</h1>");
out.println("</body></html>");
out.flush();
return;
}
chain.doFilter(request, response);

}
public void destroy() {
this.filterConfig = null;
}

上面的Filter首先判斷用戶的ip,然後截取其網絡地址,與我們屏蔽的網段比較,如果屬於屏蔽的網段,則向客戶端發送響應,並返回。這樣其它的Filter和servlet就不會執行。如果不屬於此網段,則調用FilterChain的doFilter方法,將請求交給下一個Filter處理。
以前在servlet處理包含中文的請求時總是很麻煩,servlet2.3中增加一個新的方法setCharacterEncoding用來設置請求的編碼,我們可以編寫一個設置編碼的Filter,這樣你就不必在你的每個servlet中調用這個函數,如果編碼的類型改變,你只需改變一下web.xml中的參數,而Filter和servlet的代碼則不用改變。
 

import java.servlet.*;
public class MyFilter2 implements Filter {
protected String encoding = null;
public void init(FilterConfig filterConfig) throws ServletException {
this.encoding = filterConfig.getInitParameter("encoding");
}

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {

if (request.getCharacterEncoding() == null) {
request.setCharacterEncoding(encoding);
}
chain.doFilter(request, response);

}
public void destroy() {
this.encoding = null;
}

上面代碼中的encoding是在web.xml中指定的。
部署
在web.xml描述實例2

<web-app>
<filter>
<filter-name>Filter2</filter-name> //這裏是Filter的名字,隨便你怎麼起
<filter-class>Myfilter2</filter-class> //Filter的類名,注意包含package
<init-param>
<param-name>encoding</param-name>
<param-value>gb2312</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>Filter2</filter-name>//與上面的保持一致
<url-pattern>/servlet/*</url-pattern> //對所有資源應用此filter
</filter-mapping>

</web-app>

如果一個應用有多個Filter,則在web.xml文件中,<filter-mapping>靠前的filter先執行。
 

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