Struts2拦截器之拦截器的方法过滤

在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. package com.opensymphony.xwork2.interceptor;
  17. import com.opensymphony.xwork2.ActionInvocation;
  18. import com.opensymphony.xwork2.util.TextParseUtil;
  19. import com.opensymphony.xwork2.util.logging.Logger;
  20. import com.opensymphony.xwork2.util.logging.LoggerFactory;
  21. import java.util.Collections;
  22. import java.util.Set;
  23. /**
  24. * <!-- START SNIPPET: javadoc -->
  25. *
  26. * MethodFilterInterceptor is an abstract <code>Interceptor</code> used as
  27. * a base class for interceptors that will filter execution based on method
  28. * names according to specified included/excluded method lists.
  29. *
  30. * <p/>
  31. *
  32. * Settable parameters are as follows:
  33. *
  34. * <ul>
  35. * <li>excludeMethods - method names to be excluded from interceptor processing</li>
  36. * <li>includeMethods - method names to be included in interceptor processing</li>
  37. * </ul>
  38. *
  39. * <p/>
  40. *
  41. * <b>NOTE:</b> If method name are available in both includeMethods and
  42. * excludeMethods, it will be considered as an included method:
  43. * includeMethods takes precedence over excludeMethods.
  44. *
  45. * <p/>
  46. *
  47. * Interceptors that extends this capability include:
  48. *
  49. * <ul>
  50. * <li>TokenInterceptor</li>
  51. * <li>TokenSessionStoreInterceptor</li>
  52. * <li>DefaultWorkflowInterceptor</li>
  53. * <li>ValidationInterceptor</li>
  54. * </ul>
  55. *
  56. * <!-- END SNIPPET: javadoc -->
  57. *
  58. * @author <a href='mailto:the_mindstorm[at]evolva[dot]ro'>Alexandru Popescu</a>
  59. * @author Rainer Hermanns
  60. *
  61. * @see org.apache.struts2.interceptor.TokenInterceptor
  62. * @see org.apache.struts2.interceptor.TokenSessionStoreInterceptor
  63. * @see com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor
  64. * @see com.opensymphony.xwork2.validator.ValidationInterceptor
  65. *
  66. * @version $Date: 2009-12-27 19:18:29 +0100 (Sun, 27 Dec 2009) $ $Id: MethodFilterInterceptor.java 894090 2009-12-27 18:18:29Z martinc $
  67. */
  68. public abstract class MethodFilterInterceptor extends AbstractInterceptor {
  69. protected transient Logger log = LoggerFactory.getLogger(getClass());
  70. protected Set<String> excludeMethods = Collections.emptySet();
  71. protected Set<String> includeMethods = Collections.emptySet();
  72. public void setExcludeMethods(String excludeMethods) {
  73. this.excludeMethods = TextParseUtil.commaDelimitedStringToSet(excludeMethods);
  74. }
  75. public Set<String> getExcludeMethodsSet() {
  76. return excludeMethods;
  77. }
  78. public void setIncludeMethods(String includeMethods) {
  79. this.includeMethods = TextParseUtil.commaDelimitedStringToSet(includeMethods);
  80. }
  81. public Set<String> getIncludeMethodsSet() {
  82. return includeMethods;
  83. }
  84. @Override
  85. public String intercept(ActionInvocation invocation) throws Exception {
  86. if (applyInterceptor(invocation)) {
  87. return doIntercept(invocation);
  88. }
  89. return invocation.invoke();
  90. }
  91. protected boolean applyInterceptor(ActionInvocation invocation) {
  92. String method = invocation.getProxy().getMethod();
  93. // ValidationInterceptor
  94. boolean applyMethod = MethodFilterInterceptorUtil.applyMethod(excludeMethods, includeMethods, method);
  95. if (log.isDebugEnabled()) {
  96. if (!applyMethod) {
  97. log.debug("Skipping Interceptor... Method [" + method + "] found in exclude list.");
  98. }
  99. }
  100. return applyMethod;
  101. }
  102. /**
  103. * Subclasses must override to implement the interceptor logic.
  104. *
  105. * @param invocation the action invocation
  106. * @return the result of invocation
  107. * @throws Exception
  108. */
  109. protected abstract String doIntercept(ActionInvocation invocation) throws Exception;
  110. }

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

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

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


主要方法:

①protectedabstract 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. import java.util.Date;
  3. import com.opensymphony.xwork2.ActionInvocation;
  4. import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
  5. public class FilterInterceptor extends MethodFilterInterceptor {
  6. private String name;
  7. public String getName() {
  8. return name;
  9. }
  10. public void setName(String name) {
  11. this.name = name;
  12. }
  13. @Override
  14. protected String doIntercept(ActionInvocation invocation) throws Exception {
  15. // TODO Auto-generated method stub
  16. FilterAction fa= (FilterAction)invocation.getAction();
  17. System.out.println(name+"拦截器在Action执行前拦截"+new Date());
  18. String result=invocation.invoke();
  19. System.out.println(name+"拦截器在Action执行后拦截"+new Date());
  20. return result;
  21. }
  22. }

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

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

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

三。配置文件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. </action>
  29. </package>
  30. </struts>

四。jsp视图 MethodFilter.jsp

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

五:运行结果:

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

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

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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值