struts2 拦截器拦截action中指定方法

1.继承类MethodFilterInterceptor(此类是类AbstractInterceptor的子类)

import java.util.Map;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

/*
 *拦截指定方法 
 */
public class MyFilterInterceptor  extends MethodFilterInterceptor{
 private static final long serialVersionUID = 1L;
 private String name;
    public void setName(String name)
   {
        this.name = name;
    }
 @Override
 protected String doIntercept(ActionInvocation invocation) throws Exception {
  //取得请求相关的ActionContext实例 
  ActionContext ctx = invocation.getInvocationContext(); 
  Map session = ctx.getSession(); 
  //取出名为user的Session属性 
  String user = (String)session.get("user"); 
  //如果没有登陆,或者登陆所用的用户名不是scott,都返回重新登陆 
  if (user != null && user.equals("scott") ) 
  { 
  return invocation.invoke(); 
  } 
  //没有登陆,将服务器提示设置成一个HttpServletRequest属性 
  ctx.put("tip" , "您还没有登陆,请输入scott,tiger登陆系统"); 
  //直接返回login的逻辑视图 
  return Action.LOGIN; 
 }

}

 

2.struts.xml配置

<package name="site" extends="struts-default" namespace="/site">
 <interceptors> 
 <!-- 定义了一个名为authority的拦截器 --> 
  <interceptor name="authority" class="cn.zgcyx.filter.MyFilterInterceptor"/> <!--上面自定义的拦截器类-->
  <interceptor-stack name="myDefault">
   <interceptor-ref name="authority"> <!-- 引用拦截器  -->
    <param name="includeMethods">getALL,getPart,listUser</param> <!-- 设置需要拦截的方法,多个以逗号隔开 -->
   </interceptor-ref>
   <interceptor-ref name="defaultStack"></interceptor-ref>
  </interceptor-stack>
 </interceptors>
 <default-interceptor-ref name="myDefault"></default-interceptor-ref>

  <!-- 全局 -->
 <global-results> 
  <!-- 当返回login视图名时,转入/login.jsp页面 --> 
  <result name="login">/login.jsp</result> 
 </global-results>
<action name="site" class="siteServiceAction">

  <!--省略跳转-->

</action>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值