struts2におけるAbstractInterceptorの使い方

Struts2におけるAbstractInterceptorは、Interceptorインターフェイスを実装する抽象クラスで、サブクラスが継承して利用できるメソッドとプロパティを提供しています。AbstractInterceptorを利用する手順は以下の通りです。

  1. 抽象インターセプターを継承するクラスを作成します。
public class MyInterceptor extends AbstractInterceptor {
    // 实现抽象方法
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        // 执行拦截逻辑
        // 返回结果字符串
        return invocation.invoke();
    }
}
  1. struts.xml 設定ファイルにて Interceptor を設定する
<interceptors>
    <interceptor name="myInterceptor" class="com.example.MyInterceptor"/>
    <interceptor-stack name="myInterceptorStack">
        <interceptor-ref name="myInterceptor"/>
        <interceptor-ref name="defaultStack"/>
    </interceptor-stack>
</interceptors>
  1. InterceptorをActionクラスまたはグローバル設定に利用する。
<action name="myAction" class="com.example.MyAction">
    <interceptor-ref name="myInterceptorStack"/>
    <result>/success.jsp</result>
</action>

{}ブロックでmyInterceptorというインターセプタを定義の後、defaultStack(デフォルトのインターセプタスタック)とmyInterceptorの2つのスタックを含むmyInterceptorStackというインターセプタスタックを定義しています。そしてmyActionではmyInterceptorStackというインターセプタスタックを使用しています。

上述手順を実施することで、Struts2でAbstractInterceptorを用いたカスタムのインターセプターロジックを実装することができます。

bannerAds