1. 程式人生 > >Java之struts2自定義攔截器

Java之struts2自定義攔截器

struts2自定義攔截器

攔截器生命週期:
    隨著程式的開始而建立,隨著程式的結束而銷燬
    (不可能每個訪問都建立一個攔截器)

方式一

實現Interceptor介面

public class MyInterceptor1 implements Interceptor{
    // 生命週期方法
    // 攔截器初始化方法
    @Override
    public void init() {

    }
    // 攔截方法
    @Override
    public String intercept(ActionInvocation arg0) throws
Exception { return null; } // 銷燬方法 @Override public void destroy() { } }

方式二

繼承AbstractInterceptor

public class MyInterceptor2 extends AbstractInterceptor{

    @Override
    public String intercept(ActionInvocation arg0) throws Exception {
        return null;
    }

}

方式三(使用這種)

繼承MethodFilterInterceptor(方法過濾攔截器)

public class MyInterceptor3 extends MethodFilterInterceptor{
    // 攔截方法
    @Override
    protected String doIntercept(ActionInvocation invocation) throws Exception {
        // 前處理
        System.out.println("前處理");

        <!--放行方法-->
        <!--所有攔截器都執行完畢後 會拿到一個字串-->
<!--這個字串就是action類 執行完畢後返回的字串--> String result = invocation.invoke(); // 後處理 System.out.println("後處理"); return result; } }

Action類

public class Demo01Action extends ActionSupport{

    public String add() {
        System.out.println("add");
        return "success";
    }
    public String delete() {
        System.out.println("delete");
        return "success";
    }
    public String update() {
        System.out.println("update");
        return "success";
    }
    public String find() {
        System.out.println("find");
        return "success";
    }
}

struts.xml
配置自定義攔截器(配置資訊參考struts-default.xml)

<struts>
    <package name="inter" namespace="/" extends="struts-default">
        <!-- 1.註冊攔截器 -->
        <interceptors>
            <!-- 註冊自己定義的攔截器 -->
            <interceptor name="MyInterceptor3" class="com.lanou3g.intercept.MyInterceptor3"></interceptor>
            <!-- 2.註冊攔截器棧 -->
            <interceptor-stack name="myStack">
                <!-- 引入攔截器 -->
                <interceptor-ref name="MyInterceptor3">
                    <!-- 
                        設定不想攔截的方法 逗號隔開多個方法
                        includeMethods表示設定想攔截的方法
                    -->
                    <param name="excludeMethods">add,update</param>
                </interceptor-ref>
                <!-- 除了引用自己的攔截器 還要使用系統預設攔截器 -->
                <!-- 
                    建議:先放自己的攔截器 再放系統的攔截器
                    自己寫的攔截器 可能會用到系統的攔截器封裝好的功能
                 -->
                 <!-- 引入系統預設的攔截器棧 -->
                 <interceptor-ref name="defaultStack"></interceptor-ref>
            </interceptor-stack>
        </interceptors>
        <!-- 3.設定預設攔截器棧是哪個 -->
        <default-interceptor-ref name="myStack"></default-interceptor-ref>


        <action name="Demo01Action_*" class="com.lanou3g.intercept.Demo01Action" method="{1}">
            <result name="success">/hello.jsp</result>
        </action>
    </package>
</struts>

自定義攔截器實現登入檢查

建立自定義攔截器

public class MyInterceptor extends MethodFilterInterceptor{

    @Override
    protected String doIntercept(ActionInvocation invocation) throws Exception {

        // 根據session域中 是否存放了User物件
        // 來判斷 使用者是否登入了
        Object object = ActionContext.getContext().getSession().get("user");
        if (object == null) {
            // 沒登入 重定向到登入頁面
            return "toLogin";
        } else {
            // 登入了放行
            return invocation.invoke();
        }
    }
}

Action類

public class UserAction extends ActionSupport implements ModelDriven<User>{
    // 宣告一個service
    private UserService service = new UserServiceImpl();

    // 使用模型驅動
    private User u = new User();

    // 宣告登入的action方法
    public String login() {
        System.out.println(u);

        // 呼叫service方法
        User findU = service.login(u);
        // 儲存到session域中(登入狀態)
        ActionContext.getContext().getSession().put("user", findU);

        // 表示重定向回首頁
        return "toIndex";
    }

    @Override
    public User getModel() {
        return u;
    }

}

service層

    <!--
        只根據名字查詢使用者 如果查詢出使用者(這裡包含著使用者所有資訊)
        再比對使用者的密碼是否正確
    -->
    if (findU == null) {
        // 沒有這個使用者 使用異常處理
        throw new RuntimeException("使用者不存在");
    }
    if (!findU.getUser_password().equals(u.getUser_password())) {
        // 密碼不正確
        throw new RuntimeException("密碼不正確");
    }
    // 返回查詢的物件
    return findU;

login.jsp

    <!-- 引入struts標籤庫 -->
    <%@ taglib uri="/struts-tags" prefix="s" %>

    <!-- 顯示錯誤資訊 -->
    <!-- 獲取異常資訊 message
    相當於呼叫了getMessage()方法 -->
    <font color="red">
        <s:property value="exception.message"/>
    </font>


    <!-- 檢視值棧標籤 -->
    <s:debug></s:debug>

struts.xml配置

<struts>
    <package name="web" namespace="/" extends="struts-default">
        <interceptors>
            <interceptor name="MyInterceptor" class="com.lanou3g.web.MyInterceptor"></interceptor>
            <interceptor-stack name="myStack">
                <interceptor-ref name="MyInterceptor">
                    <!-- 設定不攔截登入方法 -->
                    <param name="excludeMethods">login</param>
                </interceptor-ref>
                <interceptor-ref name="defaultStack"></interceptor-ref>
            </interceptor-stack>
        </interceptors>

        <default-interceptor-ref name="myStack"></default-interceptor-ref>      


        <!-- 設定全域性的攔截器返回結果 進行跳轉設定 -->
        <global-results>
            <result name="toLogin" type="redirect">/login.jsp</result>
        </global-results>


        <!-- 配置全域性異常處理頁面 異常的對映 -->
        <global-exception-mappings>
            <!-- exception 異常錯誤型別(全類名) -->
            <!-- result 出現異常返回的結果字串 -->
            <!-- action 可以根據這個 異常的結果 跳轉一個頁面 -->
            <exception-mapping result="error" exception="java.lang.RuntimeException"></exception-mapping>           
        </global-exception-mappings>


        <action name="UserAction_*" class="com.lanou3g.web.UserAction" method="{1}">
            <!-- 登入成功後 重定向回首頁 -->
            <result name="toIndex" type="redirect">/index.htm</result>
            <!-- 配置一個異常處理 要跳轉的頁面 -->
            <result name="error">/login.jsp</result>
        </action>
    </package>
</struts>