1. 程式人生 > >在struts2中配置自定義攔截器放行多個方法

在struts2中配置自定義攔截器放行多個方法

return med ttr limit ring req tac cat invoke

源碼:

自定義的攔截器類:

//自定義攔截器類: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;

[email protected]
  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;
}

在struts2中配置自定義攔截器放行多個方法