struts2拦截器

1.    理解拦截器

1.1.    什么是拦截器:

拦截器,在AOPAspect-Oriented Programming)中用于在某个方法或字段被访问之前,进行拦截然后在之前或之后加入某些操作。拦截是AOP的一种实现策略。

Webwork的中文文档的解释为——拦截器是动态拦截Action调用的对象。它提供了一种机制可以使开发者可以定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行。同时也是提供了一种可以提取action中可重用的部分的方式。

谈到拦截器,还有一个词大家应该知道——拦截器链(Interceptor Chain,在Struts 2中称为拦截器栈Interceptor Stack)。拦截器链就是将拦截器按一定的顺序联结成一条链。在访问被拦截的方法或字段时,拦截器链中的拦截器就会按其之前定义的顺序被调用。

1.2.    拦截器的实现原理:

大部分时候,拦截器方法都是通过代理的方式来调用的。Struts 2的拦截器实现相对简单。当请求到达Struts 2ServletDispatcher时,Struts 2会查找配置文件,并根据其配置实例化相对的拦截器对象,然后串成一个列表(list),最后一个一个地调用列表中的拦截器。如下图:

 

2.    拦截器的配置

Struts 2已经为您提供丰富多样的,功能齐全的拦截器实现。大家可以至struts2jar包内的struts-default.xml查看关于默认的拦截器与拦截器链的配置。


以下部分就是从struts-default.xml文件摘取的内容:

< interceptor name ="alias" class ="com.opensymphony.xwork2.interceptor.AliasInterceptor" /> 
< interceptor name ="autowiring" class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor" /> 
< interceptor name ="chain" class ="com.opensymphony.xwork2.interceptor.ChainingInterceptor" /> 
< interceptor name ="conversionError" class ="org.apache.struts2.interceptor.StrutsConversionErrorInterceptor" /> 
< interceptor name ="createSession" class ="org.apache.struts2.interceptor.CreateSessionInterceptor"/> 
< interceptor name ="debugging" class="org.apache.struts2.interceptor.debugging.DebuggingInterceptor" /> 
< interceptor name ="external-ref" class="com.opensymphony.xwork2.interceptor.ExternalReferencesInterceptor" /> 
< interceptor name ="execAndWait" class ="org.apache.struts2.interceptor.ExecuteAndWaitInterceptor"/> 
< interceptor name ="exception" class="com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor" /> 
< interceptor name ="fileUpload" class ="org.apache.struts2.interceptor.FileUploadInterceptor" /> 
< interceptor name ="i18n" class ="com.opensymphony.xwork2.interceptor.I18nInterceptor" /> 
< interceptor name ="logger" class ="com.opensymphony.xwork2.interceptor.LoggingInterceptor" /> 
< interceptor name ="model-driven" class="com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor" /> 
< interceptor name ="scoped-model-driven" class="com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor" /> 
< interceptor name ="params" class ="com.opensymphony.xwork2.interceptor.ParametersInterceptor" />
< interceptor name ="prepare" class ="com.opensymphony.xwork2.interceptor.PrepareInterceptor" /> 
< interceptor name ="static-params" class="com.opensymphony.xwork2.interceptor.StaticParametersInterceptor" /> 
< interceptor name ="scope" class ="org.apache.struts2.interceptor.ScopeInterceptor" /> 
< interceptor name ="servlet-config" class ="org.apache.struts2.interceptor.ServletConfigInterceptor" /> 
< interceptor name ="sessionAutowiring" class="org.apache.struts2.spring.interceptor.SessionContextAutowiringInterceptor" /> 
< interceptor name ="timer" class ="com.opensymphony.xwork2.interceptor.TimerInterceptor" /> 
< interceptor name ="token" class ="org.apache.struts2.interceptor.TokenInterceptor" /> 
< interceptor name ="token-session" class ="org.apache.struts2.interceptor.TokenSessionStoreInterceptor" /> 
< interceptor name ="validation" class ="com.opensymphony.xwork2.validator.ValidationInterceptor" /> 
< interceptor name ="workflow" class ="com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor" /> 
< interceptor name ="store" class ="org.apache.struts2.interceptor.MessageStoreInterceptor" /> 
< interceptor name ="checkbox" class ="org.apache.struts2.interceptor.CheckboxInterceptor" /> 

<   interceptor   name   ="profiling"   class   ="org.apache.struts2.interceptor.ProfilingActivationInterceptor"   />  

       struts.xml文件中定义拦截器,拦截器栈:

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

        <interceptors>

        <!-- 定义拦截器 -->

        <interceptor name="拦截器名class="拦截器实现类"/>

        <!-- 定义拦截器栈 -->

        <interceptor-stack name="拦截器栈名">

             <interceptor-ref name="拦截器一"/>

             <interceptor-ref name="拦截器二"/>

        </interceptor-stack>

        </interceptors>

        ......

</package>

3.    使用拦截器

一旦定义了拦截器和拦截器栈后,就可以使用这个拦截器或拦截器栈来拦截Action了。拦截器的拦截行为将会在Actionexceute方法执行之前被执行。

<action name="userOpt" class="org.qiujy.web.struts2.action.UserAction">

            <result name="success">/success.jsp</result>

            <result name="error">/error.jsp</result>

<!-- 使用拦截器,一般配置在result之后, -->

<!-- 引用系统默认的拦截器 -->

<interceptor-ref name="defaultStack"/>

            <interceptor-ref name="拦截器名或拦截器栈名"/>

        </action>

       此处需要注意的是,如果为Action指定了一个拦截器,则系统默认的拦截器栈将会失去作用。为了继续使用默认拦截器,所以上面配置文件中手动引入了默认拦截器。

4.    自定义拦截器

作为“框架(framework)”,可扩展性是不可或缺的。虽然,Struts 2为我们提供如此丰富的拦截器实现,但是这并不意味我们失去创建自定义拦截器的能力,恰恰相反,在Struts 2自定义拦截器是相当容易的一件事。

4.1.    实现拦截器类:

所有的Struts 2的拦截器都直接或间接实现接口com.opensymphony.xwork2.interceptor.Interceptor。该接口提供了三个方法:

1)      void init(); 在该拦截器被初始化之后,在该拦截器执行拦截之前,系统回调该方法。对于每个拦截器而言,此方法只执行一次。

2)      void destroy();该方法跟init()方法对应。在拦截器实例被销毁之前,系统将回调该方法。

3)      String intercept(ActionInvocation invocation) throws Exception; 该方法是用户需要实现的拦截动作。该方法会返回一个字符串作为逻辑视图。

除此之外,继承类com.opensymphony.xwork2.interceptor.AbstractInterceptor是更简单的一种实现拦截器类的方式,因为此类提供了init()destroy()方法的空实现,这样我们只需要实现intercept方法。

4.2.    使用自定义拦截器:

两个步骤:

l  通过<interceptor …>元素来定义拦截器。

l  通过<interceptor-ref …>元素来使用拦截器。

5.    自定义拦截器示例

5.1.    问题描述:

使用自定义拦截器来完成用户权限的控制:当浏览者需要请求执行某个操作时,应用需要先检查浏览者是否登录,以及是否有足够的权限来执行该操作。

5.2.    实现权限控制拦截器类:

AuthorizationInterceptor.java

package org.qiujy.common;

 

import java.util.Map;

 

import com.opensymphony.xwork2.Action;

import com.opensymphony.xwork2.ActionInvocation;

import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

 

 

public class AuthorizationInterceptor extends AbstractInterceptor {

 

    

    public String intercept(ActionInvocation invocation) throws Exception {

       

        Map session = invocation.getInvocationContext().getSession();

        String userName = (String) session.get("userName");

       

        if (null != userName && userName.equals("test")) {

            System.out.println("拦截器:合法用户登录---");

            return invocation.invoke();

        else {

            System.out.println("拦截器:用户未登录---");

            return Action.LOGIN;

        }

    }

}

 

5.3.    配置权限控制拦截器:

struts.xml

<!DOCTYPE struts PUBLIC

        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

        "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

    <package name="my" extends="struts-default">

       

        <interceptors>

        <!-- 定义权限控制拦截器 -->

        <interceptor name="authority"class="org.qiujy.common.AuthorizationInterceptor"/>

        </interceptors>

       

        <!-- 定义全局处理结果 -->

        <global-results>

        <!-- 逻辑名为login的结果,映射到/login.jsp页面 -->

        <result name="login">/login.jsp</result>

        </global-results>

       

        <action name="listall"class="org.qiujy.web.struts2.action.UserAction" method="listAllUser">

            <result name="success">/listall.jsp</result>

            <!-- 使用拦截器 -->

            <interceptor-ref name="defaultStack"/>

            <interceptor-ref name="authority"/>

        </action>

       

        <action name="userOpt"class="org.qiujy.web.struts2.action.UserAction">

            <result name="success">/success.jsp</result>

        </action>

    </package>

</struts>

       其它页面见源代码。

5.4.    运行调试:

在浏览器地址栏直接输入http://localhost:8080/AuthorityInterceptorDemo/listall.action 来访问,此动作配置了权限拦截器,所有被转到登录页面。

 

登录后:

 

再访问http://localhost:8080/AuthorityInterceptorDemo/listall.action 这个链接:

 

如果为了简化struts.xml文件的配置,避免在每个Action重复配置该拦截器,可以将拦截器配置成了一个默认拦截器栈。如下:

<!DOCTYPE struts PUBLIC

        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

        "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

    <package name="my" extends="struts-default">

 

        <interceptors>

            <!-- 定义权限控制拦截器 -->

            <interceptor name="authority"

                class="org.qiujy.common.AuthorizationInterceptor/>

            <!-- 定义一个包含权限控制的拦截器栈 -->

            <interceptor-stack name="mydefault">

                <interceptor-ref name="defaultStack" />

                <interceptor-ref name="authority" />

            </interceptor-stack>

        </interceptors>

       

        <!-- 定义默认拦截器 -->

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

 

        <!-- 定义全局处理结果 -->

        <global-results>

            <!-- 逻辑名为login的结果,映射到/login.jsp页面 -->

            <result name="login">/login.jsp</result>

        </global-results>

 

        <action name="listall"

            class="org.qiujy.web.struts2.action.UserAction"

            method="listAllUser">

            <result name="success">/listall.jsp</result>

        </action>

    </package>

   

    <package name="font" extends="struts-default">

        <action name="userOpt"class="org.qiujy.web.struts2.action.UserAction">

            <result name="success">/success.jsp</result>

        </action>

    </package>

</struts>

一旦在某个包下定义了默认拦截器栈,在该包下的所有action都会使用此拦截器栈。对于那些不想使用些拦截器栈的action,则应该将它放置在其它的包下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值