Struts中的拦截器栈

如何自定义一个拦截器?

自定义一个拦截器需要三步:

1 自定义一个实现Interceptor接口(或者继承自AbstractInterceptor)的类。

2 在strutx.xml中注册上一步中定义的拦截器。

3 在需要使用的Action中引用上述定义的拦截器,为了方便也可将拦截器定义为默认的拦截器,这样在不加特殊声明的情况下所有的Action都被这个拦截器拦截。

<?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>
    <!-- 开发者模式 -->
    <constant name="struts.devMode" value="true"></constant>
    <package name="my-default" abstract="true" extends="struts-default">    
        <interceptors> 
            <!-- 声明自己定义的拦截器,名字以及对应的java类 -->
            <interceptor name="myInterceptor" class="com.scx.web.intercepter.LoginIntercepter"></interceptor>
            <!-- 自定义的拦截器栈 -->
            <interceptor-stack name="myDefaultStack">
                <!-- 配置自己定义的拦截器 -->
                <interceptor-ref name="myInterceptor"></interceptor-ref>
                <!-- 配置默认的拦截器栈 -->
                <interceptor-ref name="defaultStack"></interceptor-ref>
            </interceptor-stack>
        </interceptors>
        <!-- 设置默认拦截器 -->
        <default-interceptor-ref name="myDefaultStack"/>
        <!-- 全局逻辑结果视图 -->
        <global-results>
            <result name="input">/login.jsp</result>
        </global-results>

    </package>
    <!-- 继承于上面的my-default -->
    <package name="user" extends="my-default" namespace="/user">
        <!-- 用户登录的操作方法 -->
        <action name="login" class="com.scx.web.action.UserAction" method="login">
            <interceptor-ref name="myDefaultStack">
                <!-- 在使用拦截器时给拦截器注入参数 -->
                <param name="myInteceptor.excludeMethods">login</param>
            </interceptor-ref>
            <result name="success" type="redirectAction">toMain</result>
        </action>
        <!-- 显示主页的操作方法 -->
        <action name="toMain" class="com.scx.web.action.UserAction" method="main">
            <result name="success">/main.jsp</result>
        </action>
        <!-- 显示另一个页面的操作方法 -->
        <action name="toOther" class="com.scx.web.action.UserAction" method="other">
            <result name="success">/other.jsp</result>
        </action>
    </package>
</struts>
  • 1

<package name="crm" extends="struts-default" namespace="/">
<interceptors>
<!-- 注册拦截器 -->
<interceptor name="privilegeInterceptor" class="crm.itheima.web.interceptor.PrivilegeInterceptor"></interceptor>
<!-- 配置拦截器栈 -->
<interceptor-stack name="myStack">
<interceptor-ref name="privilegeInterceptor">
<param name="excludeMethods">login,regist</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- 指定默认拦截器栈 -->
<default-interceptor-ref name="myStack"></default-interceptor-ref>
<!-- 配置全局的结果页面 -->
<global-results>
<result name="login" type="redirect">/login.jsp</result>
</global-results>


一定要注意,配置好拦截器后,后面引用就要用定义的拦截器,否则定义的拦截器可能不成功。

猜你喜欢

转载自blog.csdn.net/yilaguandemei/article/details/79927621