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

来源:互联网 发布:java线程池种类 编辑:程序博客网 时间:2024/04/28 13:11
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>