0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

🛡️ Vol.11.15 Interceptorチェーンを自作してみよう(ログ / 認証フィルタ)

Last updated at Posted at 2025-05-29

Struts2の強力な機能「Interceptor」を実践的に活用!ログ記録や認証チェックの共通処理をInterceptorとして自作し、アプリの品質と保守性を高めます。


✅ 1. Interceptorとは?

Interceptor(インターセプタ) は、Struts2において
Actionの前後に共通処理を差し込むための仕組みです。

主な用途

  • ログ出力
  • 認証チェック
  • 入力検証
  • トランザクション制御

Struts2ではAction実行前・後にInterceptorが「チェーン」で自動的に呼び出されます。


✅ 2. Interceptorの実行順イメージ

[クライアント]
   ↓
[Interceptor1] → 処理前
   ↓
[Interceptor2] → 処理前
   ↓
[Action実行]
   ↑
[Interceptor2] → 処理後
   ↑
[Interceptor1] → 処理後

✅ 3. Interceptor自作(例:ログ出力)

Step1:Interceptorクラスを作成

public class LoggingInterceptor extends AbstractInterceptor {
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        System.out.println("【ログ】Action開始: " + invocation.getAction().getClass().getName());
        String result = invocation.invoke(); // 次のInterceptor or Actionを呼び出す
        System.out.println("【ログ】Action終了: " + result);
        return result;
    }
}

✅ 4. Interceptor自作(例:認証チェック)

public class AuthInterceptor extends AbstractInterceptor {
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        Map<String, Object> session = ActionContext.getContext().getSession();
        Object user = session.get("loginUser");
        if (user == null) {
            return "login"; // 未ログインならログイン画面へリダイレクト
        }
        return invocation.invoke();
    }
}


✅ 5. struts.xmlに設定する

<struts>
  <package name="default" extends="struts-default">
    
    <!-- 独自インターセプタ定義 -->
    <interceptors>
      <interceptor name="logger" class="com.example.interceptor.LoggingInterceptor"/>
      <interceptor name="auth" class="com.example.interceptor.AuthInterceptor"/>

      <!-- チェーン構成 -->
      <interceptor-stack name="myStack">
        <interceptor-ref name="logger"/>
        <interceptor-ref name="auth"/>
        <interceptor-ref name="defaultStack"/>
      </interceptor-stack>
    </interceptors>

    <!-- Actionに適用 -->
    <action name="secureAction" class="com.example.SecureAction">
      <interceptor-ref name="myStack"/>
      <result name="success">/secure.jsp</result>
      <result name="login">/login.jsp</result>
    </action>

  </package>
</struts>

✅ 6. 実行結果(ログ)

【ログ】Action開始: com.example.SecureAction
【ログ】Action終了: success


✅ 7. Interceptorの注意点

注意点 解説
invoke() を必ず呼ぶこと 呼ばないとActionまで到達しません
戻り値で分岐できる return "login"; などで別画面へ遷移可能
順番に注意 Interceptorの順序によって動作が変わります

✅ 8. まとめ:Interceptorは「共通処理の切り出し」に最適!

  • コードを重複させずに共通処理を実装できる

  • セキュリティ・トラブル対策に非常に有効

  • interceptor-stack を使えば、柔軟に構成できる


✅ 次回予告

次はさらにStruts2のコアへ踏み込みます!

Vol.11.16:Resultタイプ完全解説(dispatcher / redirect / stream など)

画面遷移の仕組みを完全理解し、より直感的なWebフロー設計へ。


🧭 関連記事(Vol.11.xxxシリーズ)

連番 タイトル 内容分類
Vol.11.0 Struts2が提供してくれる便利機能まとめ9選 導入&概要
Vol.11.1 自動注入とステートレスActionの仕組み フレームワーク内部理解
Vol.11.2 UX改善に効く!アクション層設計と入力制御の極意(プロローグ) UX設計・アクション層総論
Vol.11.2.1 【実践編】Struts2アクション層の役割と設計パターン(Command型 / UIアクション分離など) アクション設計パターン
Vol.11.2.2 【UX重視】戻るボタン・キャンセル処理の設計手法と「戻り先管理」のスマート実装 戻り先制御とUX設計
Vol.11.2.3 【設計ノウハウ】多画面遷移時のパラメータ受け渡し・保持戦略(セッション vs hidden vs URL) パラメータ多重管理
Vol.11.2.4 【実践ガイド】ユーザー操作を考慮したアクション遷移設計(リダイレクト vs フォワードの使い分け) UX遷移設計/Result制御
Vol.11.2.5 【トラブル防止】アクション層の共通処理とメンテナブルなBaseAction設計 アクション共通化/保守性
Vol.11.3 Struts2の defaultStack とは?Interceptorの中身を詳しく追ってみる Interceptor
Vol.11.3.2 🔧 Vol.11.3.2 独自Interceptorの作り方と使い所 Struts2のカスタマイズを“実践で使えるレベル”に一歩進めよう Interceptor
Vol.11.4 入門者のための「パラメータ自動バインディング」完全理解ガイド 自動バインディング
Vol.Vol.11.4.1 入門者のための自動バインディング実践パターン集 自動バインディング
Vol.11.5 Struts2の構成理解が“実務レベル”へと進化する決定版 設定ファイル構造
Vol.11.5.1 Struts2の“画面遷移の全体像”を理解するためのマイルストーン記事 設定ファイル構造
Vol.11.6 ActionSupport の便利メソッドと国際化対応 ユーティリティ / i18n
Vol.11.7 validate() / input 戦略とUX設計 開発スタイルの違い
Vol.11.8 アノテーションベースの設定 vs XML定義の比較 開発スタイルの違い
Vol.11.9 バリデーション完全解説(XML / アノテーション) バリデーション(※Vol.8補完)
Vol.11.10 Struts2の「OGNL」ってなに?しくみと使い方をやさしく解説 式言語OGNL解説
Vol.11.11 ModelDriven インターフェースの使いどころと注意点 Model駆動開発
Vol.11.12 SessionAware と RequestAware でセッション/リクエスト管理 セッション管理
Vol.11.13 Resultタイプ完全解説(dispatcher / redirect / stream など) 遷移パターン理解
Vol.11.14 Vol.11.14 ValueStackの中身を理解する – 画面とActionの橋渡し役 Action
Vol.11.16 エラー処理と例外ハンドリングの実践パターン ハンドリング設計
Vol.11.17 Struts2でファイルアップロード機能を実装する方法 実装系Tips
Vol.11.18 非同期通信(AJAX)とStruts2の連携方法 フロント連携編
Vol.11.19 セキュリティ対策(CSRF, XSS, パラメータ偽装) セキュリティ対策
Vol.11.20 複数フォームを安全に扱う!セッション管理と動的フォームの考え方 セッション管理
Vol.11.21 Struts2でJSONを返す!REST API連携と非同期通信の基本設計 セッション管理
Vol.11.22 本番環境構成とセキュリティ設計(Apache+Tomcat+Struts2連携) 外部公開

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?