struts2 拦截器的用法

1,首先要定义一个拦截器类,并且拦截器类要实现下面的接口

com.opensymphony.xwork2.interceptor.Interceptor

 

2,然后在拦截器的方法中进行拦截代码的填写

public String intercept(ActionInvocation invocation) throws Exception {
  Object obj=ActionContext.getContext().getSession().get("user");
  if(obj!=null) return invocation.invoke();//如果用户不为空代表用户已经登陆,允许执行action中的方法
  ActionContext.getContext().put("message", "你没有权限执行此项操作");
  return "message";
 }

 

3,在struts.xml文件中进行注册,由于STRUTS2有很多自定义的拦截器,如果只注册自己的拦截器的话,那么struts2自带的拦截器将会失效,所以要将struts2的拦截器也引用过来(defaultStack)

<interceptors>
    <interceptor name="permission" class="joeho.blog.cn.interceptor.PermissInterfaceInterceptor"></interceptor>
    <interceptor-stack name="permissionStack">
     <interceptor-ref name="defaultStack" />
     <interceptor-ref name="permission" />
    </interceptor-stack> 
  </interceptors>

 

4,将拦截器添加到需要拦截的ACTION中去

 <action name="manage" class="joeho.blog.cn.action.HelloWorldAction" method="add">
   <param name="savePath">/image</param>
   <interceptor-ref name="permissionStack"></interceptor-ref>
  </action>

 

5,如果希望拦截器对包下面的所有ACTION有效,则可在包中定义

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值