转自:http://enetq.blog.51cto.com/479739/542619
在Action中使用拦截器,默认情况下回拦截Action中所有的方法,但是在某些情况下,可能只需要拦截Action中的一个或多个方法,有时候也希望不拦截某个方法,这个在Struts2中是怎么实现的呢 ?
拦截器方法过滤:让拦截器有选择的拦截Action中的某个方法!
Struts2中提供了一个MethodFilterInterceptor类,开发者自定义的拦截器只需要继承该类就可以使用这个方法过滤的功能,来拦截Action中特定的方法!
查看API文档 可以看到这个类为:
- /*
- * Copyright 2002-2006,2009 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- package com.opensymphony.xwork2.interceptor;
- import com.opensymphony.xwork2.ActionInvocation;
- import com.opensymphony.xwork2.util.TextParseUtil;
- import com.opensymphony.xwork2.util.logging.Logger;
- import com.opensymphony.xwork2.util.logging.LoggerFactory;
- import java.util.Collections;
- import java.util.Set;
- /**
- * <!-- START SNIPPET: javadoc -->
- *
- * MethodFilterInterceptor is an abstract <code>Interceptor</code> used as
- * a base class for interceptors that will filter execution based on method
- * names according to specified included/excluded method lists.
- *
- * <p/>
- *
- * Settable parameters are as follows:
- *
- * <ul>
- * <li>excludeMethods - method names to be excluded from interceptor processing</li>
- * <li>includeMethods - method names to be included in interceptor processing</li>
- * </ul>
- *
- * <p/>
- *
- * <b>NOTE:</b> If method name are available in both includeMethods and
- * excludeMethods, it will be considered as an included method:
- * includeMethods takes precedence over excludeMethods.
- *
- * <p/>
- *
- * Interceptors that extends this capability include:
- *
- * <ul>
- * <li>TokenInterceptor</li>
- * <li>TokenSessionStoreInterceptor</li>
- * <li>DefaultWorkflowInterceptor</li>
- * <li>ValidationInterceptor</li>
- * </ul>
- *
- * <!-- END SNIPPET: javadoc -->
- *
- * @author <a href='mailto:the_mindstorm[at]evolva[dot]ro'>Alexandru Popescu</a>
- * @author Rainer Hermanns
- *
- * @see org.apache.struts2.interceptor.TokenInterceptor
- * @see org.apache.struts2.interceptor.TokenSessionStoreInterceptor
- * @see com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor
- * @see com.opensymphony.xwork2.validator.ValidationInterceptor
- *
- * @version $Date: 2009-12-27 19:18:29 +0100 (Sun, 27 Dec 2009) $ $Id: MethodFilterInterceptor.java 894090 2009-12-27 18:18:29Z martinc $
- */
- public abstract class MethodFilterInterceptor extends AbstractInterceptor {
- protected transient Logger log = LoggerFactory.getLogger(getClass());
- protected Set<String> excludeMethods = Collections.emptySet();
- protected Set<String> includeMethods = Collections.emptySet();
- public void setExcludeMethods(String excludeMethods) {
- this.excludeMethods = TextParseUtil.commaDelimitedStringToSet(excludeMethods);
- }
- public Set<String> getExcludeMethodsSet() {
- return excludeMethods;
- }
- public void setIncludeMethods(String includeMethods) {
- this.includeMethods = TextParseUtil.commaDelimitedStringToSet(includeMethods);
- }
- public Set<String> getIncludeMethodsSet() {
- return includeMethods;
- }
- @Override
- public String intercept(ActionInvocation invocation) throws Exception {
- if (applyInterceptor(invocation)) {
- return doIntercept(invocation);
- }
- return invocation.invoke();
- }
- protected boolean applyInterceptor(ActionInvocation invocation) {
- String method = invocation.getProxy().getMethod();
- // ValidationInterceptor
- boolean applyMethod = MethodFilterInterceptorUtil.applyMethod(excludeMethods, includeMethods, method);
- if (log.isDebugEnabled()) {
- if (!applyMethod) {
- log.debug("Skipping Interceptor... Method [" + method + "] found in exclude list.");
- }
- }
- return applyMethod;
- }
- /**
- * Subclasses must override to implement the interceptor logic.
- *
- * @param invocation the action invocation
- * @return the result of invocation
- * @throws Exception
- */
- protected abstract String doIntercept(ActionInvocation invocation) throws Exception;
- }
是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类
- package com.yaxing.interceptor;
- import java.util.Date;
- import com.opensymphony.xwork2.ActionInvocation;
- import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
- public class FilterInterceptor 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 {
- // TODO Auto-generated method stub
- FilterAction fa= (FilterAction)invocation.getAction();
- System.out.println(name+"拦截器在Action执行前拦截"+new Date());
- String result=invocation.invoke();
- System.out.println(name+"拦截器在Action执行后拦截"+new Date());
- return result;
- }
- }
在该类中name属性用来标识拦截器的名称,方便控制台的输出
二。Action:业务控制器FilterAction.java
- package com.yaxing.interceptor;
- import com.opensymphony.xwork2.ActionSupport;
- public class FilterAction extends ActionSupport {
- private String msg;
- public String getMsg() {
- return msg;
- }
- public void setMsg(String msg) {
- this.msg = msg;
- }
- public String method1() throws Exception {
- System.out.println("Action执行方法:method1()");
- return SUCCESS;
- }
- public String method2() throws Exception {
- System.out.println("Action执行方法:method2()");
- return SUCCESS;
- }
- public String method3() throws Exception {
- System.out.println("Action执行方法:method3()");
- return SUCCESS;
- }
- }
三。配置文件struts.xml
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
- <struts>
- <package name="filterexample" extends="struts-default" namespace="/ch5">
- <interceptors>
- <!--定义拦截器-->
- <interceptor name="Myinterceptor" class="com.yaxing.interceptor.Myinterceptor"></interceptor>
- <interceptor name="SimpleInterceptor" class="com.yaxing.interceptor.SimpleInterceptor"></interceptor>
- <interceptor name="FilterInterceptor" class="com.yaxing.interceptor.FilterInterceptor"></interceptor>
- </interceptors>
- <action name="Reg" class="com.yaxing.interceptor.Reg" method="execute">
- <result name="success">/Success.jsp</result>
- <result name="input">/Reg.jsp</result>
- <interceptor-ref name="defaultStack"></interceptor-ref>
- <interceptor-ref name="SimpleInterceptor"></interceptor-ref>
- </action>
- <action name="FilterAction" class="com.yaxing.interceptor.FilterAction">
- <result name="success">/MethodFilter.jsp</result>
- <!--使用拦截器-->
- <interceptor-ref name="defaultStack"></interceptor-ref>
- <interceptor-ref name="FilterInterceptor">
- <!--拦截器黑白名单-->
- <param name="includeMethods">method1</param>
- <param name="excludeMethods">method2</param>
- <!--指定参数name的值-->
- <param name="name">FilterMethod</param>
- </interceptor-ref>
- </action>
- </package>
- </struts>
四。jsp视图 MethodFilter.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@ taglib prefix="s" uri="/struts-tags" %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>My JSP 'MethodFilter.jsp' starting page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css">
- -->
- </head>
- <body>
- <s:form id="id" action="FilterAction!method1.action">
- <s:textfield name="msg" label="请输入信息:"/>
- <s:submit value="提交"/>
- </s:form>
- </body>
- </html>
五:运行结果:
①
可以看出method1方法拦截了。而method2方法是放到了黑名单中。
②将JSP视图中action 换成FilterAction!method2.action 输出信息
因为指定method2为黑名单,不会拦截,因此是没有拦截信息的。
③将JSP视图中action 换成FilterAction!method3.action 输出信息
可以看到,虽然没有在黑名单中指定method3,因为配置文件显示指定了白名单,所以拦截器只拦截白名单中指定的方法!