SSH架構之Struts的攔截器

來源:互聯網
上載者:User

Struts的攔截器
一、概述
1、基本概念:Intercetor,即為攔截器。
1) 在Struts2中,把每一個功能都用一個個的攔截器實現;使用者想用struts的哪個功能的時候,可以自由組裝使用。
2)Struts2中,為了方便使用者對攔截器的引用,提供了攔截器棧的定義,裡面可以包含多個攔截器。
舉例:檔案夾(檔案, 檔案2) 攔截器棧(攔截器,攔截器2)
3)Struts2中,如果使用者沒有指定執行哪些攔截器,struts2有一個預設執行的棧:defaultStack;
一旦如果使用者有指定執行哪些攔截器,預設的攔截器棧就不會被執行。

攔截器的設計,就是基於組件設計的應用。

二、攔截器配置舉例
1、web.xml

2、HelloAction.java

3、自訂攔截器:HelloInterceptor.java
API:
|– Interceptor 攔截器介面
|—– AbstractInterceptor 攔截器預設實現的抽象類別。一般使用者只需要繼承此類即可繼續攔截器開發。
|– ActionInvocation 攔截器的執行狀態,調用下一個攔截器或Action。

4、struts.xml配置

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC          "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"          "http://struts.apache.org/dtds/struts-2.0.dtd"><struts>    <package name="hello" extends="struts-default">        <!-- 【攔截器配置】 -->        <interceptors>            <!-- 配置使用者自訂的攔截器 -->            <interceptor name="helloInterceptor" class="sram.interceptor.HelloInterceptor"></interceptor>            <!-- 自訂一個棧: 要引用預設棧、自訂的攔截器 -->            <interceptor-stack name="helloStack">                <!-- 引用預設棧 (一定要放到第一行)-->                <interceptor-ref name="defaultStack"></interceptor-ref>                <!-- 引用自訂攔截器 -->                <interceptor-ref name="helloInterceptor"></interceptor-ref>            </interceptor-stack>        </interceptors>        <!-- 【執行攔截器】 -->        <default-interceptor-ref name="helloStack"></default-interceptor-ref>        <!-- Action配置 -->        <action name="hello" class="sram.interceptro.HelloAction">            <result name="success">/index.jsp</result>        </action>    </package></struts>

5、執行流程:
1、結果講解:

2、時序圖講解

1)啟動:建立所有攔截器、執行init()
2)訪問:
a)先建立Action,
b)再執行攔截器,
c)最後:攔截器允許存取,執行execute();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.