转载:Struts2拦截器之拦截器的方法过滤

简介: 转自:http://enetq.blog.51cto.com/479739/542619 在Action中使用拦截器,默认情况下回拦截Action中所有的方法,但是在某些情况下,可能只需要拦截Action中的一个或多个方法,有时候也希望不拦截某个方法,这个在Struts2中是怎么实现的呢 ? 拦...

转自:http://enetq.blog.51cto.com/479739/542619

在Action中使用拦截器,默认情况下回拦截Action中所有的方法,但是在某些情况下,可能只需要拦截Action中的一个或多个方法,有时候也希望不拦截某个方法,这个在Struts2中是怎么实现的呢 ?

拦截器方法过滤:让拦截器有选择的拦截Action中的某个方法!

Struts2中提供了一个MethodFilterInterceptor类,开发者自定义的拦截器只需要继承该类就可以使用这个方法过滤的功能,来拦截Action中特定的方法!

查看API文档 可以看到这个类为:

 

  1. /*  
  2.  * Copyright 2002-2006,2009 The Apache Software Foundation.  
  3.  *   
  4.  * Licensed under the Apache License, Version 2.0 (the "License");  
  5.  * you may not use this file except in compliance with the License.  
  6.  * You may obtain a copy of the License at  
  7.  *   
  8.  *      http://www.apache.org/licenses/LICENSE-2.0  
  9.  *   
  10.  * Unless required by applicable law or agreed to in writing, software  
  11.  * distributed under the License is distributed on an "AS IS" BASIS,  
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  13.  * See the License for the specific language governing permissions and  
  14.  * limitations under the License.  
  15.  */ 
  16.  
  17. package com.opensymphony.xwork2.interceptor;  
  18.  
  19. import com.opensymphony.xwork2.ActionInvocation;  
  20. import com.opensymphony.xwork2.util.TextParseUtil;  
  21. import com.opensymphony.xwork2.util.logging.Logger;  
  22. import com.opensymphony.xwork2.util.logging.LoggerFactory;  
  23.  
  24. import java.util.Collections;  
  25. import java.util.Set;  
  26.  
  27.  
  28. /**  
  29.  * <!-- START SNIPPET: javadoc -->  
  30.  *   
  31.  * MethodFilterInterceptor is an abstract <code>Interceptor</code> used as  
  32.  * a base class for interceptors that will filter execution based on method   
  33.  * names according to specified included/excluded method lists.  
  34.  *   
  35.  * <p/>  
  36.  *   
  37.  * Settable parameters are as follows:  
  38.  *   
  39.  * <ul>  
  40.  *      <li>excludeMethods - method names to be excluded from interceptor processing</li>  
  41.  *      <li>includeMethods - method names to be included in interceptor processing</li>  
  42.  * </ul>  
  43.  *   
  44.  * <p/>  
  45.  *   
  46.  * <b>NOTE:</b> If method name are available in both includeMethods and   
  47.  * excludeMethods, it will be considered as an included method:   
  48.  * includeMethods takes precedence over excludeMethods.  
  49.  *   
  50.  * <p/>  
  51.  *   
  52.  * Interceptors that extends this capability include:  
  53.  *   
  54.  * <ul>  
  55.  *    <li>TokenInterceptor</li>  
  56.  *    <li>TokenSessionStoreInterceptor</li>  
  57.  *    <li>DefaultWorkflowInterceptor</li>  
  58.  *    <li>ValidationInterceptor</li>  
  59.  * </ul>  
  60.  *   
  61.  * <!-- END SNIPPET: javadoc -->  
  62.  *   
  63.  * @author <a href='mailto:the_mindstorm[at]evolva[dot]ro'>Alexandru Popescu</a>  
  64.  * @author Rainer Hermanns  
  65.  *   
  66.  * @see org.apache.struts2.interceptor.TokenInterceptor  
  67.  * @see org.apache.struts2.interceptor.TokenSessionStoreInterceptor  
  68.  * @see com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor  
  69.  * @see com.opensymphony.xwork2.validator.ValidationInterceptor  
  70.  *   
  71.  * @version $Date: 2009-12-27 19:18:29 +0100 (Sun, 27 Dec 2009) $ $Id: MethodFilterInterceptor.java 894090 2009-12-27 18:18:29Z martinc $  
  72.  */ 
  73. public abstract class MethodFilterInterceptor extends AbstractInterceptor {  
  74.     protected transient Logger log = LoggerFactory.getLogger(getClass());  
  75.       
  76.     protected Set<String> excludeMethods = Collections.emptySet();  
  77.     protected Set<String> includeMethods = Collections.emptySet();  
  78.  
  79.     public void setExcludeMethods(String excludeMethods) {  
  80.         this.excludeMethods = TextParseUtil.commaDelimitedStringToSet(excludeMethods);  
  81.     }  
  82.       
  83.     public Set<String> getExcludeMethodsSet() {  
  84.         return excludeMethods;  
  85.     }  
  86.  
  87.     public void setIncludeMethods(String includeMethods) {  
  88.         this.includeMethods = TextParseUtil.commaDelimitedStringToSet(includeMethods);  
  89.     }  
  90.       
  91.     public Set<String> getIncludeMethodsSet() {  
  92.         return includeMethods;  
  93.     }  
  94.  
  95.     @Override 
  96.     public String intercept(ActionInvocation invocation) throws Exception {  
  97.         if (applyInterceptor(invocation)) {  
  98.             return doIntercept(invocation);  
  99.         }   
  100.         return invocation.invoke();  
  101.     }  
  102.  
  103.     protected boolean applyInterceptor(ActionInvocation invocation) {  
  104.         String method = invocation.getProxy().getMethod();  
  105.         // ValidationInterceptor  
  106.         boolean applyMethod = MethodFilterInterceptorUtil.applyMethod(excludeMethods, includeMethods, method);  
  107.         if (log.isDebugEnabled()) {  
  108.             if (!applyMethod) {  
  109.                 log.debug("Skipping Interceptor... Method [" + method + "] found in exclude list.");  
  110.             }  
  111.         }  
  112.         return applyMethod;  
  113.     }  
  114.       
  115.     /**  
  116.      * Subclasses must override to implement the interceptor logic.  
  117.      *   
  118.      * @param invocation the action invocation  
  119.      * @return the result of invocation  
  120.      * @throws Exception  
  121.      */ 
  122.     protected abstract String doIntercept(ActionInvocation invocation) throws Exception;  
  123.       
  124. }  

是AbstractInterceptor拦截器的子类,实现了Interceptor和Serializable接口

MethodFilerInterceptor实现方法过滤中用到的两个参数

 

execludeMethods:该参数指定拦截器拒绝拦截的方法列表,多个方法用“,”隔开,指定了这个参数,拦截器不会拦截指定列表中的方法,就是所谓的黑名单
includeMethods:该参数指定拦截器需要拦截的方法列表,如果指定了参数,则指定的Action在执行前会被拦截,即白名单。

 


主要方法:

①protected abstract String doIntercept(ActionInvocation invocation) throws Exception;  必须重写此方法,实现拦截。

②String interceptor(ActionInvocation invocation):继承自AbstractInterceptor类,方法不需要强制重写

③void setExcludeMethods(String excludeMethods):设置拦截器黑名单,参数为Action一方法名。拦截器不拦截该方法

 

④void setIncludeMethods(String includeMethods):设置拦截器白名单,参数为Action一方法名。拦截器会拦截该方法

⑤Set<String> getExcludeMethodsSet():获得拦截器的黑名单

⑥Set<String> getIncludeMethodsSet():获得拦截器的白名单

 

一般开发者只需要重写doIntercept方法即可!下面给出一个实例:

一。实现方法过滤的拦截器实现类:FilterInterceptor.java继承自MethodFilterInterceptor类

 

  1. package com.yaxing.interceptor;  
  2.  
  3. import java.util.Date;  
  4.  
  5. import com.opensymphony.xwork2.ActionInvocation;  
  6. import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;  
  7.  
  8. public class FilterInterceptor extends MethodFilterInterceptor {  
  9.     private String name;  
  10.       
  11.  
  12.     public String getName() {  
  13.         return name;  
  14.     }  
  15.  
  16.  
  17.     public void setName(String name) {  
  18.         this.name = name;  
  19.     }  
  20.  
  21.  
  22.     @Override 
  23.     protected String doIntercept(ActionInvocation invocation) throws Exception {  
  24.         // TODO Auto-generated method stub  
  25.         FilterAction fa= (FilterAction)invocation.getAction();  
  26.         System.out.println(name+"拦截器在Action执行前拦截"+new Date());  
  27.         String result=invocation.invoke();  
  28.         System.out.println(name+"拦截器在Action执行后拦截"+new Date());  
  29.         return result;  
  30.     }  
  31.  
  32. }  

在该类中name属性用来标识拦截器的名称,方便控制台的输出

二。Action:业务控制器FilterAction.java

 

  1. package com.yaxing.interceptor;  
  2.  
  3. import com.opensymphony.xwork2.ActionSupport;  
  4.  
  5. public class FilterAction extends ActionSupport {  
  6.     private String msg;  
  7.  
  8.     public String getMsg() {  
  9.         return msg;  
  10.     }  
  11.  
  12.     public void setMsg(String msg) {  
  13.         this.msg = msg;  
  14.     }  
  15.     public String method1() throws Exception {  
  16.         System.out.println("Action执行方法:method1()");  
  17.         return SUCCESS;  
  18.     }  
  19.     public String method2() throws Exception {  
  20.         System.out.println("Action执行方法:method2()");  
  21.         return SUCCESS;  
  22.     }  
  23.  
  24.     public String method3() throws Exception {  
  25.         System.out.println("Action执行方法:method3()");  
  26.         return SUCCESS;  
  27.     }  
  28.  
  29.  
  30. }  

三。配置文件struts.xml

  1. <?xml version="1.0" encoding="UTF-8" ?> 
  2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> 
  3. <struts> 
  4. <package name="filterexample" extends="struts-default" namespace="/ch5"> 
  5.     <interceptors> 
  6. <!--定义拦截器-->
  7.         <interceptor name="Myinterceptor" class="com.yaxing.interceptor.Myinterceptor"></interceptor> 
  8.         <interceptor name="SimpleInterceptor" class="com.yaxing.interceptor.SimpleInterceptor"></interceptor> 
  9.         <interceptor name="FilterInterceptor" class="com.yaxing.interceptor.FilterInterceptor"></interceptor> 
  10.     </interceptors> 
  11.     <action  name="Reg" class="com.yaxing.interceptor.Reg" method="execute"> 
  12.            <result name="success">/Success.jsp</result> 
  13.            <result name="input">/Reg.jsp</result> 
  14.            <interceptor-ref name="defaultStack"></interceptor-ref> 
  15.            <interceptor-ref name="SimpleInterceptor"></interceptor-ref> 
  16.     </action> 
  17.     <action name="FilterAction" class="com.yaxing.interceptor.FilterAction"> 
  18.             <result name="success">/MethodFilter.jsp</result> 
  19. <!--使用拦截器-->
  20.             <interceptor-ref name="defaultStack"></interceptor-ref> 
  21.             <interceptor-ref name="FilterInterceptor"> 
  22. <!--拦截器黑白名单-->
  23.                  <param name="includeMethods">method1</param> 
  24.                  <param name="excludeMethods">method2</param> 
  25. <!--指定参数name的值-->
  26. <param name="name">FilterMethod</param>
  27.             </interceptor-ref> 
  28.       
  29.       
  30.     </action> 
  31.       
  32. </package> 
  33.  
  34. </struts>      

四。jsp视图 MethodFilter.jsp

 

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
  2. <%@ taglib prefix="s" uri="/struts-tags" %> 
  3.  
  4. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
  5. <html> 
  6.   <head> 
  7.       
  8.       
  9.     <title>My JSP 'MethodFilter.jsp' starting page</title> 
  10.       
  11.     <meta http-equiv="pragma" content="no-cache"> 
  12.     <meta http-equiv="cache-control" content="no-cache"> 
  13.     <meta http-equiv="expires" content="0">      
  14.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
  15.     <meta http-equiv="description" content="This is my page"> 
  16.     <!--  
  17.     <link rel="stylesheet" type="text/css" href="styles.css">  
  18.     --> 
  19.  
  20.   </head> 
  21.     
  22.   <body> 
  23.     <s:form id="id" action="FilterAction!method1.action"> 
  24.        <s:textfield name="msg" label="请输入信息:"/> 
  25.        <s:submit value="提交"/> 
  26.     </s:form> 
  27.   </body> 
  28. </html> 

五:运行结果:

 

 

可以看出method1方法拦截了。而method2方法是放到了黑名单中。

②将JSP视图中action 换成FilterAction!method2.action 输出信息

 

因为指定method2为黑名单,不会拦截,因此是没有拦截信息的。

③将JSP视图中action 换成FilterAction!method3.action 输出信息

可以看到,虽然没有在黑名单中指定method3,因为配置文件显示指定了白名单,所以拦截器只拦截白名单中指定的方法!

相关文章
|
1月前
|
Java Spring 容器
[JavaWeb]——过滤器filter与拦截器Interceptor的使用、执行过程、区别
[JavaWeb]——过滤器filter与拦截器Interceptor的使用、执行过程、区别
|
3月前
过滤器&拦截器
过滤器&拦截器
32 0
过滤器&拦截器
|
4月前
SpringMVC-拦截器参数及拦截器链配置
SpringMVC-拦截器参数及拦截器链配置
32 0
|
6月前
|
Java 容器
过滤器和拦截器的区别
Filter 也称为过滤器,基于Servlet实现,拦截器(Interceptor)是一种动态拦截方法调用的机制,在SpringMVC中动态拦截控制器方法的执行,基于AOP思想,对方法进行增强。和servlet 中的过滤器类似,都是对用户请求进行处理。
45 0
|
Java 应用服务中间件 API
过滤器和拦截器
过滤器和拦截器
139 0
|
存储 中间件 API
拦截器介绍和实际使用
拦截器介绍和实际使用
174 0
|
JSON 运维 数据格式
[SpringMVC]拦截器②(拦截器参数、拦截器链配置)
拦截器②(拦截器参数、拦截器链配置)
[SpringMVC]拦截器②(拦截器参数、拦截器链配置)
SpringMVC:拦截器和过滤器的区别
SpringMVC:拦截器和过滤器的区别
103 0
SpringMVC:拦截器和过滤器的区别
|
Java
Struts拦截器解析
Struts拦截器解析
82 0
Struts2拦截器的简单应用,登录权限拦截器及与过滤器的区别(八)上
Struts2拦截器的简单应用,登录权限拦截器及与过滤器的区别(八)
131 0
Struts2拦截器的简单应用,登录权限拦截器及与过滤器的区别(八)上