在struts2中配置自定义拦截器放行多个方法

源码:

自定义的拦截器类:

//自定义拦截器类:LoginInterceptor ;

package com.java.action.interceptor;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

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

public class LoginInterceptor extends MethodFilterInterceptor {
private static final long serialVersionUID = -5315714306081057062L;

  @Override
  protected String doIntercept(ActionInvocation invocation) throws Exception {
    //Logger log = LoggerFactory.getLogger(getClass());

    HttpSession session = ServletActionContext.getRequest().getSession();
    Object obj = session.getAttribute("boperator");
    if(null != obj ){
      //log.debug("Skipping Interceptor... Method [" + doIntercept(null) + "] found in exclude list.");
      return invocation.invoke();
     }else{
      //log.debug("Skipping Interceptor... Method [" + doIntercept(null) + "] found in exclude list.");
      return null;
    }
  }

}

在struts2.xml中配置:

 <!-- package标签下 -->

<package name="helloactionpkg" extends="struts-default" namespace="/">
<!-- 自定义 拦截器 -->
<interceptors>
<interceptor name="login" class="com.java.action.interceptor.LoginInterceptor"></interceptor>
</interceptors>

<!-- package标签内容  标签尾 -->

<!-- action标签下 -->
<action name="hello_*" class="com.java.action.UserAction" method="{1}" >
<!-- 配置拦截器 -->
<interceptor-ref name="login">

<!-- param 标签下   name="excludeMethods"   放行多个方法   方法名1,方法名2  用逗号隔开即可  -->
<param name="excludeMethods">toLogin,login</param>
</interceptor-ref>
<!-- 由于使用了自定义拦截器,应再次加载使用框架默认拦截器 -->
<interceptor-ref name="defaultStack"></interceptor-ref>

<!-- action标签内容  标签尾 -->

原因--源码(部分):

protected Set<String> excludeMethods = Collections.emptySet();
protected Set<String> includeMethods = Collections.emptySet();

public void setExcludeMethods(String excludeMethods) {
  this.excludeMethods = TextParseUtil.commaDelimitedStringToSet(excludeMethods);
}

public static Set<String> commaDelimitedStringToSet(String s) {
  Set<String> set = new HashSet<String>();
  String[] split = s.split(",");
  for (String aSplit : split) {
    String trimmed = aSplit.trim();
    if (trimmed.length() > 0)
    set.add(trimmed);
  }
  return set;
}

原文地址:https://www.cnblogs.com/moly/p/6830020.html