【Servlet】サーブレットフィルタ ~ Filter ~

はじめに

http://blogs.yahoo.co.jp/dk521123/33567439.html
でログイン機能を実装してみたが、ログイン認証後のページ(WelcomeView.jsp)を
直接URLを叩いた場合、閲覧できてしまう。
そんな時に便利な「フィルタ機能」を調べてみた。

用途

http://mergedoc.sourceforge.jp/tomcat-servletapi-5-ja/javax/servlet/Filter.html
より抜粋。(1)と2)はどのシステムでも使えると思う)

1) 認証フィルタ 
2) ログと監査フィルタ (デバッグログも含む)
3) イメージ変換フィルタ 
4) データ圧縮フィルタ 
5) 暗号化フィルタ 
6) トークン分割(Tokenizing)フィルタ 
7) リソースアクセスイベントのトリガとなるフィルタ 
8) XSL/T フィルタ 
9) Mime-type チェーンフィルタ

他にも、以下が考えらる

10) エンコーディング

サンプル

 * その他のコードは下記の関連記事を参照のこと。
http://blogs.yahoo.co.jp/dk521123/33567439.html

SampleFilter.java

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.HttpSession;

import com.sample.models.LoginModel;

/**
 * Servlet Filter implementation class SampleFilter
 */
public class SampleFilter implements Filter {
	private FilterConfig filterConfig;

	/**
	 * Default constructor.
	 */
	public SampleFilter() {
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		this.filterConfig.getServletContext().log("Starting Filtering");

		try {
			HttpServletRequest httpServletRequest = (HttpServletRequest) request;
			HttpSession session = httpServletRequest.getSession();
			HttpServletResponse httpServletResponse = (HttpServletResponse) response;
			if (session == null) {
				/* まだ認証されていない */
				this.filterConfig.getServletContext().log("Invalid User1");
				httpServletResponse.sendRedirect(httpServletRequest
						.getContextPath() + "/Views/LoginView.jsp");
			} else {
				Object loginModel = session.getAttribute("loginModel");

				if (loginModel instanceof LoginModel == false
						|| ((LoginModel) loginModel).isValidUser() == false) {
					/* まだ認証されていない */
					this.filterConfig.getServletContext().log("Invalid User2 ");
					httpServletResponse.sendRedirect(httpServletRequest
							.getContextPath() + "/Views/LoginView.jsp");
				}
			}
		} catch (Exception ex) {
			this.filterConfig.getServletContext().log("Error from Filter", ex);
		}
		// pass the request along the filter chain
		chain.doFilter(request, response);

		this.filterConfig.getServletContext().log("Finished Filtering");
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}
}

web.xml

一部。注目ポイントは、<url-pattern>
<?xml version="1.0" encoding="UTF-8"?>
  <!-- 省略 -->
  <filter>
    <display-name>SampleFilter</display-name>
    <filter-name>SampleFilter</filter-name>
    <filter-class>com.sample.filter.SampleFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>SampleFilter</filter-name>
    <url-pattern>/Views/Logon/*</url-pattern>
  </filter-mapping>
</web-app>

出力結果

直接URLを叩いた場合
情報: Starting Filtering
6 04, 2014 11:37:23 午後 org.apache.catalina.core.ApplicationContext log
情報: Invalid User2 
6 04, 2014 11:37:23 午後 org.apache.catalina.core.ApplicationContext log
情報: Finished Filtering


関連記事

Servlet + JSP でログイン機能を実装する

http://blogs.yahoo.co.jp/dk521123/33567439.html

リスナー ~ Listener ~

http://blogs.yahoo.co.jp/dk521123/33573219.html

デザインパターン】Chain of Responsibilityパターン ~ 責任の連鎖 ~

 * サーブレットフィルタは、Chain of Responsibilityパターンによって実現している
http://blogs.yahoo.co.jp/dk521123/33576955.html
http://blogs.yahoo.co.jp/dk521123/33576935.html