您的位置:首页 > 编程语言 > Java开发

struts拦截器

2016-01-04 16:48 459 查看

struts拦截器

配置拦截器

<interceptors>
<interceptor name="" class="">
<!--拦截器栈-->
<interceptor-stack name="">
<interceptor-ref name="">
</interceptor-stack>
</interceptor>


2.默认拦截器

<!--将拦截器myintertceptor配置为默认拦截器-->
<default-interceptor-ref name="myInterceptor"/>


在struts.xml配置一个包时,可以为其指定默认拦截器,一旦指定了,如果该包中的Action
没有指定其他拦截器,则默认拦截器会起作用.
如果需要多个拦截器作为默认拦截器,定义成一个拦截器栈


3. 实现拦截器类

自定义拦截器需要实现.Interceptor接口,该接口提供了三个方法

public interface Interceptor extrends Serializable{
void init();
void destroy();
String Intercept(ActionInvocation invocation) throws Exception;
}


public abstract class AbstractInterceptor implements Interceptor{
public void init(){}
public void destroy(){}
public abstract String Intercept(ActionInvocation invocation) throws Exception;


AbstractInterceptor类提供了init()和destroy()方法的空实现,并且会在程序开始和结束时各执行一遍。

自定义拦截器,只需继承这个抽象类,在struts.xml定义自定义的拦截器,在struts.xml中的Action中使用拦截器。

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

public class MyInterceptor extends AbstractInterceptor{

@Override
public String intercept(ActionInvocation arg0) throws Exception{
System.out.println("拦截器正在运行");
String resultString =arg0.invoke();
System.out.println("拦截器已经结束....");
return resultString;
}
}


ActionInvocation参数是对被拦截Action的一个引用,invoke总是映射到第一个拦截器

通过调用该参数的invoke方法,将控制权传给下一个拦截器或Action的execute方法或者返回一个

控制字符串停止后续的拦截器.

4.拦截器的方法过滤

在Action中使用拦截器,默认情况下回拦截Action中所有的方法,但是在某些情况下,可能只需要

拦截Action中的一个或多个方法,有时候也希望不拦截某个方法。

MethodFilterInterceptor抽象类,该类继承了AbstractInterceptor,并重写了interceptor()方法,

同时还提供了doInterceptor()的抽象方法,用户可以自定义拦截逻辑,实现方法和Abstract类似。

在MethodFilterInterceptor提供了两个重要方法:

setExcludeMethods(String excludeMethods):设置不需要过滤的方法。

setIncludeMethods(String excludeMethods):设置需要过滤的方法。如果出现冲突,以次为准。

<interceptor-ref name="">
<parm name="excludeMethods">excute,register</parm>
</interceptor-ref>


5.使用拦截器实现权限控制

拦截器的invocation参数可以轻易的访问到请求相关的ActionContext实例。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: