天天看點

Interceptor的簡單使用

1.寫一個類,testinterceptor 實作了interceptor的接口,在這裡我們可以做任何事情,通常我做的是權限的攔截,可以根據你想要實作的功能來命名你的interceptor,比如權限的攔截器,可以取名checkprivilegeinterceptor。下面是攔截器類的代碼

testinterceptor

package com.ssh.interceptor;

import com.opensymphony.xwork2.actioninvocation;

import com.opensymphony.xwork2.interceptor.interceptor;

public class testinterceptor implements interceptor {

    public void destroy() {

        system.out.println("---->> testinterceptor ---->> destory()");

    }

    public void init() {

        system.out.println("---->> testinterceptor ---->> init()");

    public string intercept(actioninvocation invocation) throws exception {

        system.out.println("---->> testinterceptor ---->> before()");

        invocation.invoke();

        system.out.println("---->> testinterceptor ---->> after()");

        return "test";

}

2.在你的struts.xml的配置檔案裡面配置剛剛的攔截器類就行了

struts.xml:

    <package name="default" namespace="/" extends="struts-default">

        <!-- 配置攔截器棧 預設的攔截器棧名為defaultstack -->

        <interceptors>

            <interceptor name="testinterceptor" class="com.ssh.interceptor.testinterceptor">

            </interceptor>

            <interceptor-stack name="defaultstack">

                <interceptor-ref name="testinterceptor"></interceptor-ref>

                  <interceptor-ref name="defaultstack"></interceptor-ref>

            </interceptor-stack>

        </interceptors>

   </package>

3.重新部署一下項目,檢視控制台,如果沒什麼exception就沒什麼問題。