ログイン認証のインターセプター

  • jp.co.foo.interceptor.LoginAuthInterceptor

セッションスコープオブジェクトに"userSession"が無い場合はLoginAuthExceptionをthrowする。

package jp.co.foo.interceptor;

import javax.servlet.http.HttpSession;

import jp.co.foo.exception.LoginAuthException;

import org.aopalliance.intercept.MethodInvocation;
import org.seasar.framework.aop.interceptors.AbstractInterceptor;
import org.seasar.framework.container.S2Container;

public class LoginAuthInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = 3925021926996430042L;

	protected S2Container container;

	public Object invoke(MethodInvocation invocation) throws Throwable {
		Object ret = null;
		Boolean loginFlg = isSessionAttribute("userSession");
		System.out.println("### BEGIN LoginAuthInterceptor ###");
		if (loginFlg == null || !loginFlg.booleanValue()) {
			throw new LoginAuthException();
		}
		Throwable cause = null;
		try {
			ret = invocation.proceed();
		} catch (final Throwable t) {
			cause = t;
		}
		System.out.println("### END LoginAuthInterceptor ###");
		if (cause != null) {
			throw cause;
		}
		return ret;
	}

	public S2Container getContainer() {
		return this.container;
	}

	public void setContainer(S2Container container) {
		this.container = container.getRoot();
	}

	private Boolean isSessionAttribute(String key) {
		HttpSession session = (HttpSession) container.getExternalContext()
				.getSession();
		return session.getAttribute(key) != null ? true : false;
	}
}

インターセプターをコンポーネント登録。

<component name="loginAuthInterceptor" class="jp.co.foo.interceptor.LoginAuthInterceptor"/>
  • customizer.dicon

loginAuthCustomizerをコンポーネント登録。jp.co.foo.action.implの"To"、"Login"で始まるクラスには適用しない。interceptorNameはaop.diconで登録したインターセプター。
actionCustomizerにloginAuthCustomizerを登録。

<component name="loginAuthCustomizer" class="org.seasar.framework.container.customizer.AspectCustomizer" instance="singleton" autoBinding="auto" externalBinding="false">
    <property name="interceptorName" bindingType="should">"aop.loginAuthInterceptor"</property> 
	<initMethod name="addIgnoreClassPattern">
		<arg>"jp.co.foo.action.impl"</arg>
		<arg>"To.*, Login.*"</arg>
	</initMethod>
</component>


<component name="actionCustomizer" class="org.seasar.framework.container.customizer.CustomizerChain">
	<!-- 追加部分 -->	
	<initMethod name="addCustomizer">
		<arg>loginAuthCustomizer</arg>
	</initMethod>
	<!-- 追加部分 -->
		
	<initMethod name="addCustomizer">
		<arg>traceCustomizer</arg>
	</initMethod>
</component>

これで、"To"、"Login"以外で始まるactionクラスを実行する前に"userSession"の有無チェックを行い、あった場合のみactionクラスのメソッドを呼び出す。