struts攔截器使用

一:書寫攔截器類java

package cn.itcast.myintercepter;

import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

/**
* @author 做者
* @version 建立時間:2018年7月26日 下午2:42:24
* 類說明:攔截器建立方式
*     繼承:MethodFilterIntercepter方法過濾攔截器
*    功能:定製攔截器攔截的方法
*        定製哪些方法須要攔截哪些方法不須要攔截
*/
public class MyInterceptor extends MethodFilterInterceptor {

    @Override
    protected String doIntercept(ActionInvocation invocation) throws Exception {
        //1.得到session
        Map<String, Object> session = ActionContext.getContext().getSession();
        //2.得到登錄標識
        Object object = session.get("user");
        //3.判斷登錄標識是否存在
        if(object==null) {
            //說明沒有登錄,重定向到登錄頁面
            return "toLogin";
        }else {
            //說明登錄=》放行
            return invocation.invoke();
        }        
    }

}
攔截器類

二:配置struts文件web

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <package name="crm" namespace="/" extends="struts-default">
        <!-- 配置攔截器步驟 -->
        <interceptors>
        <!-- 1.註冊攔截器 -->
            <interceptor name="myIntercator" class="cn.itcast.myintercepter.MyInterceptor"></interceptor>
        <!-- 2.註冊攔截器棧-->
            <interceptor-stack name="myStack">
            <!-- 自定義攔截器棧 -->
            <interceptor-ref name="myIntercator">
                <!-- 不須要攔截的方法名 -->
                <param name="excludeMethods">login</param>
            </interceptor-ref>
            <!-- 引用默認的攔截器棧(20個) -->
            <interceptor-ref name="defaultStack"></interceptor-ref>
            </interceptor-stack>
        </interceptors>
        <!-- 3.指定默認的攔截器棧 -->
        <default-interceptor-ref name="myStack"></default-interceptor-ref>
        <!-- 定義全局結果集 -->
        <global-results>
            <result name="toLogin" type="redirect">/login.jsp</result>
        </global-results>
        <global-exception-mappings>
            <!-- 若是出現java.lang.RuntimeException異常,就將跳轉到名爲error的結果 -->
            <exception-mapping result="error" exception="java.lang.RuntimeException"></exception-mapping>
        </global-exception-mappings>
            
        <action name="UserAction_*" class="cn.itcast.web.UserAction" method ="{1}">
            <result name="toHome" type="redirect">/index.htm</result>
        </action>
    </package>
</struts>
struts配置文件
相關文章
相關標籤/搜索