Struts2自定义拦截器

如果用户要开发自己的拦截器类,应该实现com.opensymphony.xwork2.interceptor.Interceptor接口,该接口的类定义代码如下:

public interface Interceptor extends Serializable{
          //销毁拦截器前的回调方法
          void destory();
          //初始拦截器的回调方法
          void init();
          //拦截器实现拦截的逻辑方法
          String intercept (ActionInvocation invocation) throws Exception;
}

Struts2还提供了一个AbstractInterceptor类(Interceptor的实现类),该类提供了一个init()和destroy()方法的空实现,如果实现的拦截器不需要打开资源,则可以无须实现这两个方法。继承此类只需重写一个方法,较方便。

@SuppressWarnings("serial")
public class SessionInterceptor extends AbstractInterceptor {
	private static final Object LOGIN_KEY = "admin";
	public static final String LOGIN_PAGE = "loginPage";

	@Override
	public String intercept(ActionInvocation actionInvocation) throws Exception {
		Map session = actionInvocation.getInvocationContext().getSession();
		Admin admin = (Admin) session.get(LOGIN_KEY);
		if (admin != null) {
                        //执行该拦截器的后一个拦截器
                        //如果该拦截器后没有其他拦截器,则执行Action的被拦截方法
			return actionInvocation.invoke();
		} else {
			return LOGIN_PAGE;
		}
	}
}

使用自定义拦截器时需要在struts.xml中配置。

1.通过<interceptor.../>元素来定义拦截器。

2.通过<interceptor-ref.../>元素来使用拦截器。

<package name="default" extends="struts-default">
		<interceptors>
			<interceptor name="SessionInterceptor"
				class="net.csdn.action.interceptors.SessionInterceptor" />
		</interceptors>
                <action name="myAction"
			class="net.csdn.action.myAction">
			<result name="input">/xx.jsp</result>
			<result type="chain">xxx</result>
			<interceptor-ref name="defaultStack" />
			<interceptor-ref name="SessionInterceptor" />
		</action>
</package>

注意:如果为Action指定了一个拦截器,则系统默认的拦截器将会失去作用。为了继续使用默认拦截器,所以上面配置文件中显示地应用了默认拦截器。

到此,简单的自定义拦截器完成了。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值