Chinaunix首页 | 论坛 | 博客
  • 博客访问: 280737
  • 博文数量: 93
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 830
  • 用 户 组: 普通用户
  • 注册时间: 2016-02-25 10:44
个人简介

一杯茶,一台电脑

文章分类

全部博文(93)

文章存档

2018年(4)

2017年(57)

2016年(32)

分类: Java

2017-06-09 09:35:00

转自:http://www.blogjava.net/i369/articles/162407.html

如何使用struts2拦截器,或者自定义拦截器。特别注意,在使用拦截器的时候,在Action里面必须最后一定要引用struts2自带的拦截器缺省堆栈defaultStack,如下(这里我是引用了struts2自带的checkbox拦截器):

  0

(必须加,否则出错)

也可以改为对全局Action设置自己需要的拦截器,如下:

在struts.xml里面定义全局的配置设置
  extends="struts-default">
   
      myStack">
       
          0
      

       
     

   

    (这句是设置所有Action自动调用的拦截器堆栈)
 

 
struts-action.xml里面配置Action如下:
  extends="struts-shop">(这里扩展struts.xml里面定义的配置就可以了)
  
     /jsp/smeishop/admin/index.jsp
     /jsp/smeishop/admin/logon.jsp
     /jsp/smeishop/admin/logon.jsp
  

  
     /jsp/smeishop/admin/logon.jsp
  

 

你的拦截器可以正常工作了!!HOHO

以下是参考资料


Struts2 拦截器 [Interceptor]

拦截器的工作原理如上图,每一个Action请求都包装在一系列的拦截器的内部。拦截器可以在Action执行直线做相似的操作也可以在Action执行直后做回收操作。

 

每一个Action既可以将操作转交给下面的拦截器,Action也可以直接退出操作返回客户既定的画面。

 

如何自定义一个拦截器?

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

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

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

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

 

Interceptor接口声明了三个方法:

 

public interface Interceptor extends Serializable {

 

    void destroy();

 

    void init();

 

    String intercept(ActionInvocation invocation) throws Exception;

}

 

Init方法在拦截器类被创建之后,在对Action镜像拦截之前调用,相当于一个post-constructor方法,使用这个方法可以给拦截器类做必要的初始话操作。

 

Destroy方法在拦截器被垃圾回收之前调用,用来回收init方法初始化的资源。

 

Intercept是拦截器的主要拦截方法,如果需要调用后续的Action或者拦截器,只需要在该方法中调用invocation.invoke()方法即可,在该方法调用的前后可以插入Action调用前后拦截器需要做的方法。如果不需要调用后续的方法,则返回一个String类型的对象即可,例如Action.SUCCESS。

另外AbstractInterceptor提供了一个简单的Interceptor的实现,这个实现为:

public abstract class AbstractInterceptor implements Interceptor {

 

     public void init() {

    }

   

    public void destroy() {

    }

 

 

    public abstract String intercept(ActionInvocation invocation) throws Exception;

}

在不需要编写init和destroy方法的时候,只需要从AbstractInterceptor继承而来,实现intercept方法即可。

 

我们尝试编写一个Session过滤用的拦截器,该拦截器查看用户Session中是否存在特定的属性(LOGIN属性)如果不存在,中止后续操作定位到LOGIN,否则执行原定操作,代码为:

public class CheckLoginInterceptor extends AbstractInterceptor {

    public static final String LOGIN_KEY = "LOGIN";

    public static final String LOGIN_PAGE = "global.login";

 

    public String intercept(ActionInvocation actionInvocation) throws Exception {

 

        System.out.println("begin check login interceptor!");

        // 对LoginAction不做该项拦截

        Object action = actionInvocation.getAction();

        if (action instanceof LoginAction) {

            System.out.println("exit check login, because this is login action.");

            return actionInvocation.invoke();

        }

 

        // 确认Session中是否存在LOGIN

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

        String login = (String) session.get(LOGIN_KEY);

        if (login != null && login.length() > 0) {

            // 存在的情况下进行后续操作。

            System.out.println("already login!");

            return actionInvocation.invoke();

        } else {

            // 否则终止后续操作,返回LOGIN

            System.out.println("no login, forward login page!");

            return LOGIN_PAGE;

        }

    }

}

 

注册拦截器

           

name="login" 

class="com.jpleasure.teamware.util.CheckLoginInterceptor"/>

           

               

               

           

 

将上述拦截器设定为默认拦截器:

这样在后续同一个package内部的所有Action执行之前都会被login拦截。

 

 

Struts2(XWork)提供的拦截器的功能说明:

 

拦截器

名字

说明

Alias Interceptor

alias

在不同请求之间将请求参数在不同名字件转换,请求内容不变

Chaining Interceptor

chain

让前一个Action的属性可以被后一个Action访问,现在和chain类型的result()结合使用。

Checkbox Interceptor

checkbox

添加了checkbox自动处理代码,将没有选中的checkbox的内容设定为false,而html默认情况下不提交没有选中的checkbox

Cookies Interceptor

cookies

使用配置的name,value来是指cookies

Conversion Error Interceptor

conversionError

将错误从ActionContext中添加到Action的属性字段中。

Create Session Interceptor

createSession

自动的创建HttpSession,用来为需要使用到HttpSession的拦截器服务。

Debugging Interceptor

debugging

提供不同的调试用的页面来展现内部的数据状况。

Execute and Wait Interceptor

execAndWait

在后台执行Action,同时将用户带到一个中间的等待页面。

Exception Interceptor

exception

将异常定位到一个画面

File Upload Interceptor

fileUpload

提供文件上传功能

I18n Interceptor

i18n

记录用户选择的locale

Logger Interceptor

logger

输出Action的名字

Message Store Interceptor

store

存储或者访问实现ValidationAware接口的Action类出现的消息,错误,字段错误等。

Model Driven Interceptor

model-driven

如果一个类实现了ModelDriven,将getModel得到的结果放在Value Stack中。

Scoped Model Driven

scoped-model-driven

如果一个Action实现了ScopedModelDriven,则这个拦截器会从相应的Scope中取出model调用Action的setModel方法将其放入Action内部。

Parameters Interceptor

params

将请求中的参数设置到Action中去。

Prepare Interceptor

prepare

如果Acton实现了Preparable,则该拦截器调用Action类的prepare方法。

Scope Interceptor

scope

Action状态存入session和application的简单方法。

Servlet Config Interceptor

servletConfig

提供访问HttpServletRequest和HttpServletResponse的方法,以Map的方式访问。

Static Parameters Interceptor

staticParams

struts.xml文件中将中的中的内容设置到对应的Action中。

Roles Interceptor

roles

确定用户是否具有JAAS指定的Role,否则不予执行。

Timer Interceptor

timer

输出Action执行的时间

Token Interceptor

token

通过Token来避免双击

Token Session Interceptor

tokenSession

Token Interceptor一样,不过双击的时候把请求的数据存储在Session

Validation Interceptor

validation

使用action-validation.xml文件中定义的内容校验提交的数据。

Workflow Interceptor

workflow

调用Action的validate方法,一旦有错误返回,重新定位到INPUT画面

Parameter Filter Interceptor

N/A

从参数列表中删除不必要的参数

Profiling Interceptor

profiling

通过参数激活profile

 

注册并引用Interceptor

  

      

      

  

 

  

       

       

        login.jsp

       

            type="redirect-action">/secure/home

  

 

可以将多个拦截器合并在一起作为一个堆栈调用,当一个拦截器堆栈被附加到一个Action的时候,要想Action执行,必须执行拦截器堆栈中的每一个拦截器。

  

       

       

       

          

          

       

   

 

   

        

         login.jsp

        

             type="redirect-action">/secure/home

   

 

上述说明的拦截器在默认的Struts2应用中,根据惯例配置了若干个拦截器堆栈,详细情参看struts-default.xml

其中有一个拦截器堆栈比较特殊,他会应用在默认的每一个Action上。

   

   

   

   

   

   

   

   

   

   

   

   

   

   

      dojo"..*

   

   

   

        input,back,cancel,browse

   

   

        input,back,cancel,browse

   

 

每一个拦截器都可以配置参数,有两种方式配置参数,一是针对每一个拦截器定义参数,二是针对一个拦截器堆栈统一定义所有的参数,例如:

 myValidationExcudeMethod

 myWorkflowExcludeMethod

或者

    myValidationExcludeMethod

    myWorkflowExcludeMethod

 

每一个拦截器都有两个默认的参数:

excludeMethods - 过滤掉不使用拦截器的方法和

includeMethods – 使用拦截器的方法。

 

需要说明的几点:

1 拦截器执行的顺序按照定义的顺序执行,例如:

 

 

 

 

的执行顺序为:

thisWillRunFirstInterceptor

 thisWillRunNextInterceptor

    followedByThisInterceptor

      thisWillRunLastInterceptor

        MyAction1

        MyAction2 (chain)

        MyPreResultListener

        MyResult (result)

      thisWillRunLastInterceptor

    followedByThisInterceptor

 thisWillRunNextInterceptor

thisWillRunFirstInterceptor

 

2 使用默认拦截器配置每个Action都需要的拦截器堆栈,例如:

    

    

    

 

     login.jsp

     /secure/home

可以按照如下的方式定义:

    

       

       

        

    

 

 

       login.jsp

       /secure/home

 

3 如何访问HttpServletRequest,HttpServletResponse或者HttpSession

有两种方法可以达到效果,使用ActionContext

Map attibutes = ActionContext.getContext().getSession();

或者实现相应的接口:

HttpSession            SessionAware

HttpServletRequest     ServletRequestAware

HttpServletResponse    ServletResponseAware




阅读(728) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~