Chinaunix首页 | 论坛 | 博客
  • 博客访问: 327683
  • 博文数量: 96
  • 博客积分: 2041
  • 博客等级: 大尉
  • 技术积分: 1080
  • 用 户 组: 普通用户
  • 注册时间: 2012-01-20 14:08
文章分类

全部博文(96)

文章存档

2015年(2)

2013年(1)

2012年(93)

分类: 系统运维

2012-01-23 21:51:13

拦截器是Struts2的核心, Struts2的众多功能都是通过拦截器来实现的。

拦截器类似过滤器,以下是过滤器的工作原理图:(拦截器与其相同)

([北京圣思园Struts2应用开发详解]_021.Struts2拦截器深度解读.wmv)[00.03.56.497]

 

 

拦截器的配置:

1 编写实现Interceptor接口的类

2在struts.xml中定义拦截器(两个地方有新代码)

3在action中使用拦截器

 

TheInterceptor1.java

package com.shengsiyuan.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class TheInterceptor1 implements Interceptor
{
    private String test ;

    public String getTest()
    {
        return test;
    }

    public void setTest(String test)
    {
        this.test = test;
    }

    public void destroy()
    {
        // TODO Auto-generated method stub

    }

    public void init()
    {

        System.out.println("test:"+this.test);
    }

    public String intercept(ActionInvocation invocation) throws Exception
    {
        System.out.println("before");
        String result = invocation.invoke();
        System.out.println("after");
        return result ;
    }

}

 

struts.xml


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

   
       
           

shengsiyuan


       
       
            /usernameInvalid.jsp
            /passwordInvalid.jsp
       

       
           
           
       

       
            /result.jsp
            /login.jsp
       

       
           
            action2
            ${username}
            ${password}
            ${usernameAndPassword}
          
       
           


           //默认时,没指定时用此拦截器

      
     
   

 

当访问action1.jsp时,显示顺序:init—>before—>after

一旦定义了自己的拦截器,将其配置到action上后,我们需要在action的最后加上默认的拦截器栈:defaultStack。

在配置拦截器时,可赋值参数shengsiyuan ,这样就会直接调用TheInterceptor中的setTest方法,且在init之前执行。

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