Home

2009年3月18日 星期三

[JAVA] Filtering 過濾器的使用

From: Polin Wei

Servlet 2.3 規則中最重要的新特性- Filtering , 它相容於 Servlet 2.3 規格的 J2EE 容器(Context)間快速地成為最常被用到的增值特性.

過濾器 (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 中的 <filter> 定義中所指定的. 若無則回傳 null

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的參數
<filter>
    <filter-name>loggerFilter</filter-name>
    <filter-class>com.demos.filter.LoggerFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>loggerFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>


<filter-mapping> 的樣式可以對 URL 或 servlet 來作 Filter:

<url-pattern>/*</url-pattern>
<servlet-name>action</servlet-name>



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 也要相對的加入
<filter>
    <filter-name>Set Character Encoding</filter-name>
    <filter-class>
        com.gu.filters.SetCharacterEncodingFilter
    </filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>utf-8</param-value>
    </init-param>
    <init-param>
        <param-name>ignore</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>Set Character Encoding</filter-name>
    <servlet-name>action</servlet-name>
</filter-mapping>

2009年3月6日 星期五

[Java] 建立由 LDAP AD 認證的機制

From: Polin Wei

環境:
OS : Windows Server 2k3
Domain: mydomain.com
Host : x.x.x.x(此為指定 ip address)

以 Java 程式撰寫 對 LDAP-AD 的認證, 程式碼如下:

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
 /**
     * AD LDAP 登入認證
     *
     * @param ldap_url   like ldap://x.x.x.x:389/DC=mydomain,DC=com
     * @param account
     * @param password
     * @return String[0] array 0 :0 success,1 fail,2 LDAP connect fail,3 unknow
     */
    public String[] LDAP_AUTH_AD(String ldap_url, String account, String password) {
        String[] returnStr = new String[2];
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ldap_url);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, account+"@mydomain.com");
        env.put(Context.SECURITY_CREDENTIALS, password);

        LdapContext ctx = null;
        try {
            ctx = new InitialLdapContext(env, null);
            returnStr[0] = "0";
        } catch (javax.naming.AuthenticationException e) {
            returnStr[0] = "1";

            return returnStr;
        } catch (javax.naming.CommunicationException e) {
            // System.out.println("Can't connect to ldap server!");
            returnStr[0] = "2";

            return returnStr;
        } catch (Exception e) {
            System.out.println("error");
            e.printStackTrace();
            returnStr[0] = "3";

            return returnStr;
        } finally {
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (NamingException e) {

                }
            }
        }
    }

2009年3月2日 星期一

資訊名詞簡寫速查

From: Polin Wei

資訊名詞簡寫 & 資訊名詞全名
---------------------------
BPM: Business Process Management (企業流程管理)
SOA: Service-Oriented Architecture (服務導向架構)
BPEL: Business Process Excution Language (企業流程執行語言)
BPMN: Business Process Modeling Notation (企業流程模型符號)
XPDL: XML-based Process Definition Language (以 XML 為基礎的程序定義語言)
BAM: Business Activity Monitor (商業活動監控)
UDDI: Universal Description Discovery and Integration (通用描述發現與整合)
WSDL: Web Services Description Language (全球資訊網路服務描述語言)
J2EE: Java 2 Platform Enterprise Edition (Java2 平台企業版)
PKI: Public Key Infrastructure (公開金鑰基礎建設)
EMBA: Executive Master of Business Administration (高階管理碩士班)
ROI: Return On Investment。 (投資報酬率),計算公式為:ROI = (1 + g) * n /PER。 簡介 其中,g代表企業未來n 年平均獲利成長率。PER表示本益比。
TCO: Total cost of ownership (總所有成本)