Struts2 拦截器详细配置过程

来源:互联网 发布:剑灵小正太捏脸数据 编辑:程序博客网 时间:2024/06/04 23:35

struts2中使用自定义拦截器
 虽然Strtus2框架提供了许多拦截器,这些内置的拦截器实现了Struts2的大部分功能,因此大部分web应用程序的通用功能都可以通过直接使用这些拦截器来完成,但还有一些系统逻辑相关的通用功能,则可以通过自定义拦截器来实现。值得称道的是,Struts2的拦截器系统是如此的简单,易用。

一:实现拦截器
如果程序员要开发自己的拦截器类,应该实现com.opensymphony.xwork2.interceptor接口,该接口代码如下(struts2源码):
package com.opensymphony.xwork2.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import java.io.Serializable;

public abstract interface Interceptor extendsSerializable
{
  public abstract void destroy();

  public abstract void init();

  public abstract Stringintercept(ActionInvocation paramActionInvocation)
    throwsException;
}
该接口定义了三个方法:
1,init():在该拦截器被初始化之后,在该拦截器执行拦截之前,系统将回调该方法,init()方法主要是用于打开一些资源,例如数据库资源。该方法只执行一次。
2,destroy():该方法与init()方法对应,在拦截器销毁之前,系统将回调该拦截器的destroy方法,该方法用于释放init方法中打开的资源。
3,intercept(ActionInvocationparamActionInvocation):该方法是用户需要拦截动作。就像Action的execute方法一样,intercept方法会返回一个字符串作为逻辑视图,如果该方法直接返回了一个字符串,系统将会跳转到该逻辑视图对应地实际视图资源,不会调用被拦截的Action。该方法的(ActionInvocation参数包含了被拦截的action的引用,可以通过调用该参数的invoke方法,将控制权转给下一个拦截器,或者转到action的exctute方法。

除此之外,Struts2还提供了一个com.opensymphony.xwork2.ActionInvocation.AbstractInterceptor抽象类,该类实现了com.opensymphony.xwork2.interceptor接口,则无需实现init和destory方法,自定义拦截器继承com.opensymphony.xwork2.ActionInvocation.AbstractInterceptor,实现起来会更简单
二:下面是一个简单的控制登陆访问的拦截器

package com.test.demo.web.interceptor;

import java.util.Map;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
importcom.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.test.demo.constants.Constants;
import com.test.demo.model.Userinfo;


public class UserAuthorityInterceptor extends AbstractInterceptor{

 
 @Override
 public String intercept(ActionInvocationinvocation) throws Exception {
  //取得请求相关的ActionContext实例
  ActionContext ctx =invocation.getInvocationContext();
  Map session =ctx.getSession();
  // 取出名为user的session属性
  Userinfo user = (Userinfo)session.get(Constants.SESSION_USER);
  // 如果没有登陆, 返回重新登陆
  if (user != null) {
   returninvocation.invoke();
  }
  //没有登陆,将服务器提示设置成一个HttpServletRequest属性
  ctx.put("tip","您还没有登录,请登陆系统");
  return Action.LOGIN;
 }

}
三:在struts.xml文件中配置拦截器

    "-//ApacheSoftware Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">


 

 
 
  namespace="/system">
  
  
  
   
   
    class="com.test.demo.web.interceptor.ExceptionInterceptor">
   
   
   
    class="com.test.demo.web.interceptor.UserAuthorityInterceptor">
   
   
   
    
    
   
  

  
  

  
  
   /error.jsp
   /login.jsp
  

  
  
   
    result="error">
   
  
  
  
  
  
   /success.jsp
   /error.jsp
  

  
  
   /login.jsp
  
 


 
 
  namespace="/official">

 

0 0
原创粉丝点击