struts2---中的自定义拦截器(16)

来源:互联网 发布:it资产管理 编辑:程序博客网 时间:2024/06/04 18:17

16、struts2中的自定义拦截器
业务需求:
如果用户登录-->访问action中的所有方法
如果用户没有登录,不允许访问action中的方法,并提示没有权限执行该操作
user.jsp{
 //设置用户登录的状态,放session中
}
request.getSession().getAttribute("user","itcast");
request.getSession().removeAttribute("user");

拦截器要实现拦截器的接口
public class PermissionInterceptor implements Interceptor{
 public void destory(){};
 public void init(){};
 public String intercept(ActionInvocation invocation) throws Exception{
  return null;
 }
}
struts启动时会实例化拦截器,用init(),主要是interceptor拦截Action
invocation.invoke();
public String intercept(ActionInvocation invocation) throws Exception{
 Object user=ActionContext.getContext().getSession().get("user");
 if(user!=null") return invocation.invoke();
 ActionContext.getContext().put("message","你没有访问权限";
 return "success";
}
定义拦截器
<interceptor name="permission" class="cn.itcast.interceptor.PermissionInterceptor"/>
</interceptor>
<global-result>
 <result name="success">/WEB-INF/page/message.jsp</result>
</global-result>
在Action使用拦截器
<action name="list_*" class="cn.itcast.action.HelloWordAction method="{1}">
 <interceptor-ref name="permission"/>
</action>
上面会短路内置的拦截器
<interceptor-stack name="permissionStack">
 <interceptor-ref name="defaultStack">
 </interceptor-ref>
 <interceptor-ref name="permission"/>
</interceptor-stack>

<default-interceptor-ref name="permissionStack"/>
在包底下的Action都可以运用这个拦截器
如果action引用了默认就会实现
如果在action中运用多个就添加多个

原创粉丝点击