サーブレットのフィルタFilterの詳細

6279 ワード

1.フィルタの概念
JavaのFilterは標準的なサーブレットではなく、ユーザー要求を処理したり、クライアントに応答したりすることはできません.主にHttpServertRequestの前処理に用いられるが、HttpServertResponseの後処理も可能であり、典型的な処理チェーンである.
利点:フィルタチェーンの利点は、chainを実行しない限り、実行中にいつでも中断できることです.doFilter()は、後のフィルタやリクエストの内容を実行しません.実際に使用する場合は、フィルタチェーンの実行順序の問題に特に注意しなければならない.
2.フィルタの作用説明
  • HttpServletRequestがServletに到着する前に、お客様のHttpServletRequestをブロックします.
  • 必要に応じてHttpServeretRequestをチェックしたり、HttpServeretRequestヘッダとデータを変更したりすることができます.
  • HttpServeretResponseがクライアントに到着する前に、HttpServeretResponseをブロックする.
  • 必要に応じてHttpServeretResponseをチェックし、HttpServeretResponseヘッダとデータを変更できます.

  • 3.フィルタの実行フロー
    4.Filterインタフェース
    1.駆動方法
    Webアプリケーションが起動すると、WebサーバはWebに従う.xmlファイルの構成情報は、登録された各Filterインスタンスオブジェクトを作成し、サーバのメモリに保存します.
    2.方法紹介
  • init()InitメソッドはFilterライフサイクルで1回のみ実行され、webコンテナはinitメソッドを呼び出すとき
  • である.
  • destory()は、WebコンテナがFilterオブジェクトをアンインストールする前に呼び出される.このメソッドはFilterのライフサイクルで1回のみ実行されます.この方法では、フィルタで使用されるリソースを解放することができる.
  • doFilter()Filterチェーンの実行

  • 5.FilterChainインタフェース
    1.インスタンス化方法
    現在のFilterチェーンを表すオブジェクト.コンテナによって実現され、コンテナはそのインスタンスをパラメータとしてフィルタオブジェクトのdoFilter()メソッドに入力する.
    2.作用
    フィルタチェーンの次のフィルタを呼び出す
    フィルタの例:
    web.xml構成
    
     	
     		setCharacterEncoding
     		com.company.strutstudy.web.servletstudy.filter.EncodingFilter
     		
     			encoding
     			utf-8
     		
     	
     	
     		setCharacterEncoding
     		/*
     	
     
    
     	
     		logfilter
     		com.company.strutstudy.web.servletstudy.filter.LogFilter
     	
     	
     		logfilter
     		/*
     	

    エンコーディングブロッキング:
    public class EncodingFilter implements Filter {
     	private String encoding;
     	private Map params = new HashMap();
     	//             
     	public void destroy() {
     		System.out.println("end do the encoding filter!");
     		params=null;
     		encoding=null;
     	}
     	public void doFilter(ServletRequest req, ServletResponse resp,
     			FilterChain chain) throws IOException, ServletException {
     		//UtilTimerStack.push("EncodingFilter_doFilter:");
     		System.out.println("before encoding " + encoding + " filter!");
     		req.setCharacterEncoding(encoding);
     		// resp.setCharacterEncoding(encoding);
     		// resp.setContentType("text/html;charset="+encoding);
     		chain.doFilter(req, resp);		
     		System.out.println("after encoding " + encoding + " filter!");
     		System.err.println("----------------------------------------");
     		//UtilTimerStack.pop("EncodingFilter_doFilter:");
     	}
     
     	//             
     	public void init(FilterConfig config) throws ServletException {
     		System.out.println("begin do the encoding filter!");
     		encoding = config.getInitParameter("encoding");
     		for (Enumeration e = config.getInitParameterNames(); e
     				.hasMoreElements();) {
     			String name = (String) e.nextElement();
     			String value = config.getInitParameter(name);
     			params.put(name, value);
     		}
     	}
     }
    ログブロック:
    public class LogFilter implements Filter {
     	FilterConfig config;
     
     	public void destroy() {
     		this.config = null;
     	}
     
     	public void doFilter(ServletRequest req, ServletResponse res,
     			FilterChain chain) throws IOException, ServletException {
     		//   ServletContext   ,      
     		ServletContext context = this.config.getServletContext();
     		//long before = System.currentTimeMillis();
     		System.out.println("before the log filter!");
     		//context.log("    ");
     		//       HttpServletRequest   
     		HttpServletRequest hreq = (HttpServletRequest) req;
     		//     
     		System.out.println("Log Filter             :"+hreq.getServletPath() );
     		//context.log("Filter             : " + hreq.getServletPath());
     		try {
     			// Filter       ,           。
     			chain.doFilter(req, res);
     		} catch (Exception e) {
     			e.printStackTrace();
     		}
     		System.out.println("after the log filter!");
     		//long after = System.currentTimeMillis();
     		//     
     		//context.log("    ");
     		//       
     		//context.log("       " + ((HttpServletRequest) req).getRequestURI()
     		//		+ "      : " + (after - before));
     	}
     
     	public void init(FilterConfig config) throws ServletException {
     		System.out.println("begin do the log filter!");
     		this.config = config;
     	}
     
     }
    HelloServiceクラス:
    public class HelloWorldServlet extends HttpServlet{
     
     	/**
     	 *   httpservlet   service    ,     controll      (   )
     	 *             doget,dopost    	
     	 */
     	@Override
     	protected void service(HttpServletRequest req, HttpServletResponse resp)
     			throws ServletException, IOException {
     		System.out.println("doservice..."+this.getInitParameter("encoding"));
     		
     		super.service(req, resp);
     	}
     
     	@Override
     	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     			throws ServletException, IOException {
     		System.out.println("doget...");
     		doPost(req, resp);
     	}
     
     	@Override
     	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
     			throws ServletException, IOException {
     		System.out.println("dopost...");
     	}
     	
     	
     
     }
    結果:
    before encoding utf-8 filter!
      before the log filter!
      Log Filter             :/hello
      doservice...UTF-8
      doget...
      dopost...
      after the log filter!
      after encoding utf-8 filter!
      ----------------------------------------

    まとめ:
    1.フィルタ実行プロセス
    2.常用フィルター