当前位置: 代码迷 >> 综合 >> SSH-Struts2简单的自定义拦截器MethodFilterInterceptor
  详细解决方案

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

热度:40   发布时间:2024-01-18 09:38:22.0


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。



  相关解决方案