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

Struts2-拦截器的使用方法

2018-03-20 12:08 316 查看

定义拦截器

要是用拦截器,要先在包里面定义拦截器或者拦截器栈

<interceptors >
<interceptor name="my1" class="com.cuixiaoming.interceptor.MyInterceptor1" ></interceptor>
<interceptor name="my2" class="com.cuixiaoming.interceptor.MyInterceptor2">
<param name="excludeMethods" >show2</param>
</interceptor>
<interceptor-stack name="defaultStack"></interceptor-stack>
</interceptors>


自定义拦截器

1.实现Interceptor 接口

实现接口后,在intercept方法里写逻辑

return actionInvocation.invoke();

代表放行

也可以和action一样,return “success”这种在Action标签中配置好的

package com.cuixiaoming.interceptor;

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

public class MyInterceptor1 implements Interceptor {
@Override
public void destroy() {

}

@Override
public void init() {

}

@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
System.out.println("我的1号拦截器运行了");

return actionInvocation.invoke();
}
}


2.继承MethodFilterInterceptor类

继承MethodFilterInterceptor这个类的方法是为了配置中不过滤某个方法

package com.cuixiaoming.interceptor;

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

public class MyInterceptor2 extends MethodFilterInterceptor {

@Override
protected String doIntercept(ActionInvocation actionInvocation) throws Exception {

System.out.println("我定义的2号拦截器");
return actionInvocation.invoke();
}
}


下面是忽略show1方法

<interceptor-ref name="my2">
<param name="excludeMethods" >show1</param>
</interceptor-ref>


3.继承AbstractInterceptor类

继承继承AbstractInterceptor类,需要重写intercept方法,

package com.cuixiaoming.interceptor;

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

//AbstractInterceptor
public class MyInterceptor3 extends AbstractInterceptor {

@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
System.out.println("自己定义的3号拦截器运行了");
return actionInvocation.invoke();
}
}


使用拦截器

1.配置全包默认拦截器

将已经声明的自定义拦截器,或者包继承的包中含有的拦截器的name填入,也可以将拦截器栈的name填入

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


2.在Action中配置特有拦截器

在Action中也可以配置

<action name="t1_*"  class="com.cuixiaoming.action.TestAction" method="{1}" >
<interceptor-ref name="my2"></interceptor-ref>
<result name="success" >success.jsp</result>
</action>


3.让拦截器放弃对某些方法的拦截权

首先,要想实现这种效果,需要让自定义的拦截器继承MethodFilterInterceptor类

然后可以在任何声明或使用拦截器的地方使用
<param name="excludeMethods" >
标签,标签的内部直接填写具有拦截豁免权的方法名

<interceptor-ref name="my2">
4000

<param name="excludeMethods" >show1</param>
</interceptor-ref>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  struts2 框架 ssh