struts2中的方法过滤拦截器

方法过滤拦截器是只过滤指定的方法,如果使用针对action 的普通的过滤器则会过滤该action内部 所有方法。如果在一个action中同时有多个作为业务逻辑控制的方法存在 的话则会过滤所有的业务逻辑控制方法。当然在一个action中出现超过一个业务逻辑控制方法是不推荐的,也是不符合编码规范的但是这样的形式是可以存在的。为了避免这样的bug采用方法过滤器是最佳选择。

配置文件为:

<action name="login" class="com.inspur.action.LoginAction">
   <result name="success">/success.jsp</result>
   <result name="input">/login.jsp</result>
   <interceptor-ref name="defaultStack"></interceptor-ref>
   <interceptor-ref name="methodInterceptor">
    <param name="name">second</param>
    <param name="excludeMethods">execute</param>
    <param name="includeMethods">execute</param>
   </interceptor-ref>
  </action>

方法过滤器类代码如下:

package com.inspur.interceptor;

import java.util.Date;

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

public class MethodInter extends MethodFilterInterceptor {
 private String name;
 

 public String getName() {
  return name;
 }


 public void setName(String name) {
  this.name = name;
 }


 @Override
 protected String doIntercept(ActionInvocation invocation) throws Exception {
  System.out.println(name+"start time"+new Date());
  long start=System.currentTimeMillis();
  String result=invocation.invoke();
  System.out.println(name+"end time"+new Date());
  long end=System.currentTimeMillis();
  System.out.println("total time"+(end-start));
  return result;
 }

}

重写抽象类MethodFilterInterceptor的回调方法dointercept()方法实现方法拦截。与普通的拦截器的区别是普通拦截器重写的是intercept()方法。

原文地址:https://www.cnblogs.com/moonfans/p/3165148.html