過濾器 (Filtering) 可以在資源被取出前或取出後插手檢查, 以 HTTP 為主的 請求(Request) / 回應(Response) 的中間層伺服器來說, 過濾器 (Filtering) 可以用來:
1. 在請求(Request)的表頭到達資源手中前先看看其中的內容
2. 在請求(Request)的表頭被送達資源時看看其中的內容
3. 提供修改過的請求(Request)被容器(Context)所處理過的資源
4. 在回應(Response)被傳回前, 先行存取並修改
5. 在請求(Request)到逹資源前全部加以終止
過濾器 (Filtering) 為 javax.servlet.Filter 的介面類別, 這類別所該實作的部份有三個方法:
1. doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
這是 過濾器 (Filtering) 的主要方法, 幾乎所有 過濾器 (Filtering) 的工作都在此完成. 在這個方法中需呼叫 chain.doFilter(request, response) 這個方法, 以便將控制傳給下一個過濾器 ( Pass control on to the next filter )
2. init(FilterConfig fConfig)
在 doFilter() 方法被第一次呼叫前設定 FilterConfig 物件. FilterConfig 物件提供 過濾器 (Filtering) 的初始化參數, 並允許它存取相關的 ServletContext.
3. destroy()
當 過濾器 (Filtering) 被帶出服務前, 容器(Context)會呼叫 destroy()
上述所提的 FilterConfig 物件在 init(FilterConfig fConfig) 時會取得, 而 FilterConfig 可以被 過濾器 (Filtering) 用來取得這個 過濾器 (Filtering) 的初始化參數, 文字型名稱, 或正在執行的 ServletContext. 它主要有四個方法:
1. getFilterName()
取得 過濾器 (Filtering) 定義於配置描述檔 web.xml 中的文字型名稱.
2. getInitParameter(String paramName)
取得所指定的初始化參數的字串值. 找不到則回傳 null
3. getInitParameterNames()
取得一個 java.util.Enumeration , 其中含有所有這個實體中所具有的初始化參數的名稱. 這些參數都是在配置描述元 web.xml 中的
4. getServletContext()
取得正在其中執行的 ServletConext . 這個內容通常是在伺服器上的 server.xml 檔中指定.
程式實作:
step 01: 先建立一個 LoggerFilter.java
package com.demos.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* Servlet Filter implementation class LoggerFilter
*/
public class LoggerFilter implements Filter {
protected FilterConfig filterConfig = null;
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
this.filterConfig = null;
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (filterConfig==null)
return;
long bef = System.currentTimeMillis();
ServletContext context = filterConfig.getServletContext();
context.log("in LoggerFilter Class");
// Pass control on to the next filter
chain.doFilter(request, response);
long aft = System.currentTimeMillis();
context.log("Request to " + request.getRemoteHost() + "Total time(ms): " + (aft - bef));
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
this.filterConfig = fConfig;
}
}
step 02: 在 web.xml 上加入Filter的參數
loggerFilter
com.demos.filter.LoggerFilter
loggerFilter
/*
/*
action
step 03: 在 console 中看的結果如下:
2009/3/18 下午 6:36:30 org.apache.catalina.core.ApplicationContext log
資訊: in LoggerFilter Class
2009/3/18 下午 6:36:31 org.apache.catalina.core.ApplicationContext log
資訊: Request to 127.0.0.1Total time(ms): 234
實際系統上運用 Filtering 可以讓系統在每一個網頁在載入時, 塞入編碼原則為 UTF-8 , 以避免網頁出現亂碼. 程式碼SetCharacterEncodingFilter.java如下:
/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Craig McClanahan
* @version $Revision: 1.2 $ $Date: 2004/03/18 16:40:28 $
*/
package com.demos.filters;
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;
public class SetCharacterEncodingFilter implements Filter {
// ----------------------------------------------------- Instance Variables
/**
* The default character encoding to set for requests that pass through
* this filter.
*/
protected String encoding = null;
/**
* The filter configuration object we are associated with. If this value
* is null, this filter instance is not currently configured.
*/
protected FilterConfig filterConfig = null;
/**
* Should a character encoding specified by the client be ignored?
*/
protected boolean ignore = true;
// --------------------------------------------------------- Public Methods
/**
* Take this filter out of service.
*/
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}
/**
* Select and set (if specified) the character encoding to be used to
* interpret request parameters for this request.
*
* @param request The servlet request we are processing
* @param result The servlet response we are creating
* @param chain The filter chain we are processing
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
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);
}
/**
* Place this filter into service.
*
* @param filterConfig The filter configuration object
*/
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 Methods
protected String selectEncoding(ServletRequest request) {
return (this.encoding);
}
}
而 web.xml 也要相對的加入
Set Character Encoding
com.gu.filters.SetCharacterEncodingFilter
encoding
utf-8
ignore
true
Set Character Encoding
action
From: Polin Wei
沒有留言:
張貼留言