SSH-Struts2简单的自定义拦截器MethodFilterInterceptor


SSH-Struts2简单的自定义拦截器MethodFilterInterceptor

 

   最近业余时间工作之余也在学习SSH相关的知识,今天刚刚尝试写了一个基础的Struts2拦截器通过继承MethodFilterInterceptor方法。


   一、什么是拦截器


拦截器是动态拦截Action调用的对象。它提供了一种机制可以使开发者可以定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行,同时也提供了一种可以提取action中可重用部分的方式。


二、本文的实现


1、定义一个拦截器

import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

/**
 *权限校验的拦截器
 * @author CodyLee
 *
 */
public class PrivilegeInterceptor extends MethodFilterInterceptor{
	@Override
	//执行拦截的方法
	protected String doIntercept(ActionInvocation actionInvocation) throws Exception{
		//判断是否登陆,如果登陆,放行;如果没有登陆,跳转到登陆页面
		AdminUser adminUser = (AdminUser)ServletActionContext.getRequest().getSession().getAttribute("existAdminUser");
		if(adminUser != null){
			//已经登陆过
			return actionInvocation.invoke();
		}else{
			//跳转到登陆页面
			ActionSupport support = (ActionSupport)actionInvocation.getAction();
			support.addActionError("您还没有登陆!没有权限访问!");
			return ActionSupport.LOGIN;
		}
	} 
}

2、配置自定义拦截器

<!-- 配置自定义拦截器 -->
<interceptors>
		<interceptor name="privilegeInterceptor" class="cn.itcast.shop.interceptor.PrivilegeInterceptor"/>			
</interceptors>

   3、Action中添加拦截器

<action name="adminCategory_*" class="adminCategoryAction" method="{1}">
			<result name="findAll">/admin/category/list.jsp</result>
			<interceptor-ref name="privilegeInterceptor"/>
			<interceptor-ref name="defaultStack"/> 
</action>


三、注意事项


在Struts2中拦截器的接口是Interceptor而其实现类AbstractInterceptor是Interceptor的实现类,接口中的一般方法都实现了;本文中所用到的MethodFilterInterceptor又继承了AbstractInterceptor。



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值