Struts2 拦截器详细配置过程拦截指定的一个方法或多个方法教程汇总



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在执行前会被拦截,即白名单。

 


主要方法:

①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. 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,因为配置文件显示指定了白名单,所以拦截器只拦截白名单中指定的方法!

 

本文出自 “幽灵柯南的技术blog” 博客,请务必保留此出处http://enetq.blog.51cto.com/479739/542619

http://www.cnblogs.com/ribavnu/archive/2013/03/15/2960891.html

Struts2 拦截器详细配置过程

1:所有拦截器的超级接口Interceptor ,Action去实现这个接口;

 Interceptor 它其中有三个方法(init(),destroy() ,interceptor()):

      Init()方法:在服务器起动的时候加载一次,并且只加载一次;

      Destroy()方法:当拦截器销毁时执行的方法;

      Interceptor()方法:其中里边有一个参数invocation

public String intercept(ActionInvocation invocation) throws xception {

       System.out.println(“interceptor!!”);

       String result=invocation.invoke();

       return result;

    }

Invocation.invoke()是如果只有一个拦截器执行完这个方法后,会返回给视图,如果有多个拦截器,它顺序的执行完所有的拦截器,才返回给视图.

2:可以在系统初始化中给拦截器指定默认的参数(也包括了定义拦截器方式)如下:

    在拦截器类中把hello当做属性set/get方式注入到拦截器类中;

      <interceptors>

           <!– 先定义拦截器 –>

           <interceptor name=”myInterceptor” class=”com.zzz.struts2.interceptor.MyInterceptor”>

              <!– 指定系统初始化给拦截器的参数 –>

              <param name=”hello”>张钊钊</param>

           </interceptor>

           <!– 加到自己设置的拦截器栈里边去 –>

           <interceptor-stack name=”myStack”>

              <interceptor-ref name=”myInterceptor”>

              </interceptor-ref>

              <interceptor-ref name=”defaultStack”></interceptor-ref>

           </interceptor-stack>

       </interceptors>

       <!– 改变系统默认的拦截器,改成自己的默认拦截器,并且一个系统只能有一个默认的拦截器,这样这个拦截器栈会默认应用到所有的Action上去 –>

       <default-interceptor-ref name=”myStack”>

       </default-interceptor-ref>

       也可以在使用拦截器的时候给它设置参数:

       就是在一个action 的reslut下面配置上如下:

    <action name=”register”

           class=”com.zzz.struts2.action.RegisterAction”>

           <result name=”success”>/success.jsp</result>

           <!– result 它其中还有一个信息转发类型 type=”"记住,如果不转向JSP,转向图表,可以改变type=”"值 –>

           <result name=”input”>/register.jsp</result>

          

           <interceptor-ref name=”myInterceptor”>

              <param name=”hello”>welcome</param>

           </interceptor-ref>

           <interceptor-ref name=”myStack”></interceptor-ref>

       </action>

2.拦截器,拦截器栈和默认的拦截器之间的关系

1:拦截器和拦截器栈是一个级别的,也就是说一个拦截器栈中包括许多拦截器, 一个拦截器栈中还可以包括许多拦截器栈,配置如下方式:

<interceptors>

           <!– 先定义拦截器 –>

           <interceptor name=”myInterceptor” class=”com.zzz.struts2.interceptor.MyInterceptor”>

              <!– 指定系统初始化给拦截器的参数 –>

              <param name=”hello”>张钊钊</param>

           </interceptor>

           <!– 加到自己设置的拦截器栈里边去 –>

           <interceptor-stack name=”myStack”>

              <interceptor-ref name=”myInterceptor”>

              </interceptor-ref>

              <interceptor-ref name=”defaultStack”></interceptor-ref>

           </interceptor-stack>

       </interceptors>

拦截器的使用:1.先定义;2.在引用使用;

<interceptor name=”myInterceptor” class=”com.zzz.struts2.interceptor.MyInterceptor”>

<interceptor-ref name=”myInterceptor”>

              </interceptor-ref>

 2:struts2中有一个系统默认的拦截器栈是 defaultStack,如果你手动引用自己的拦截器,系统默认的拦截器栈将不起作用;这样必需手动引入系统的拦截器栈<interceptor-ref name=”defaultStack”>

              </interceptor-ref>

如果想改变系统默认的拦截器栈,可以这样配置:

<default-interceptor-ref name=”myStack”>

</default-interceptor-ref>其中myStack是自己定义的拦截器栈名字;

如果拦截器栈中有多个拦截器,在执行action之前的顺序跟配置拦截器的顺序一致,而在action之后执行的顺序是相反的;

 

3:抽象的拦截器类AbstractInterceptor

1:Interceptor这个超级拦截器接口,有三方法需要实现,但是如果不想使用init();

    destroy()方法,可以去继承这个抽象拦截器类;

它的使用跟上边的没有什么区别;

 

4:方法过滤拦截器MethodFilterInterceptor

1:上边的拦截器都要是针对整个action的,如果针对某个方法进行拦截可以去继承这个类;

它的使用跟上边的使用方法差不多,只是需要要配置它对那个方法进行拦截,方法过滤拦截器最好不要配置到自己设置默认的拦截器栈里边,自己手动配置.

interceptor-ref name=”myInterceptor3″>

              <param name=”includeMethods”>execute</param>

              <param name=”excludeMethods”>execute</param>

           </interceptor-ref>

           <interceptor-ref name=”defaultStack”></interceptor-ref>

其中includeMethods ,excludeMethods是固定写法: includeMethods 包含拦截那些方法,多个方法需要用”,”隔开; excludeMehtods是排除拦截的那些方法;

5:鉴听器PreResultListener接口

1:它的鉴听点在拦截器执行完某个action方法后,在渲染视图之前做一些事情;让某个类去实现这个接口;

然后向需要它的拦截器中注册进去如下代码:

publicclass MyInterceptor3 extends MethodFilterInterceptor {

    privatestaticfinallongserialVersionUID = 3756655410194005443L;

    @Override

    protected String doIntercept(ActionInvocation invocation) throws Exception {

       //把鉴听器注册到拦截中去;

       invocation.addPreResultListener(new MyListener());

       System.out.println(“my Interceptor3″);

       String result=arg0.invoke();

       System.out.println(“my interceptor3 finshed!”);

       return result;

    }

}http://blog.sina.com.cn/s/blog_67196ddc0100ncnh.html

Struts2自定义拦截器实例—登陆权限验证

分类: SSH 2010-04-22 09:21 63809人阅读 评论(50) 收藏 举报

版本:struts2.1.6

此实例实现功能:用户需要指定用户名登陆,登陆成功进入相应页面执行操作,否则返回到登陆页面进行登陆,当直接访问操作页面(登陆后才能访问的页面)时则不允许,须返回登陆页面。

代码如下:

一、页面

login.jsp

  1. <%@ page language=”java” import=”java.util.*” pageEncoding=”UTF-8″%>
  2. <!DOCTYPE HTML PUBLIC ”-//W3C//DTD HTML 4.01 Transitional//EN”>
  3. <html>
  4.   <head>
  5.     <title>yuewei’Login</title>
  6.     <!–
  7.     <link rel=”stylesheet” type=”text/css” href=”styles.css” mce_href=”styles.css”>
  8.     –>
  9.   </head>
  10.   <body>
  11.   <form action=”login.action” method=”post”>
  12.   User:<input type=”text” name=”username”><br>
  13.   Passoword:<input type=”password” name=”password”><br>
  14.   <input type=”submit” value=”submit”>
  15.   </form>
  16. </body>
  17. </html>

 

welcome.jsp

  1. <%@ page language=”java” import=”java.util.*” pageEncoding=”UTF-8″%>
  2. <!DOCTYPE HTML PUBLIC ”-//W3C//DTD HTML 4.01 Transitional//EN”>
  3. <html>
  4.   <head>
  5.     <title> yuewei’s Welcome</title>
  6.  <!–
  7.  <link rel=”stylesheet” type=”text/css” href=”styles.css” mce_href=”styles.css”>
  8.  –>
  9.   </head>
  10.   <body>
  11.   <h1>登录成功后显示此页面</h1>
  12.   <a href=”show.action” mce_href=”show.action”>show</a>
  13.   </body>
  14. </html>

 

show.jsp

  1. <%@ page language=”java” import=”java.util.*” pageEncoding=”UTF-8″%>
  2. <!DOCTYPE HTML PUBLIC ”-//W3C//DTD HTML 4.01 Transitional//EN”>
  3. <html>
  4.   <head>
  5.     <title>yuewei’s Show</title>
  6.     <!–
  7.     <link rel=”stylesheet” type=”text/css” href=”styles.css” mce_href=”styles.css”>
  8.     –>
  9.   </head>
  10.   <body>
  11.     Show This Page
  12.         登录后执行此页面<br>
  13.   </body>
  14. </html>

 

 

二、Action

LoginFormAction

  1. package com.ywjava.action;
  2. import com.opensymphony.xwork2.ActionSupport;
  3. public class LoginFormAction extends ActionSupport {
  4.     public String exexcute() {
  5.         return ”success”;
  6.     }
  7. }

 

LoginAction

  1. package com.ywjava.action;
  2. import com.opensymphony.xwork2.ActionContext;
  3. import com.opensymphony.xwork2.ActionSupport;
  4. import com.ywjava.utils.Constants;
  5. public class LoginAction extends  ActionSupport{
  6. private String username;
  7. private String password;
  8. public String getPassword() {
  9.     return password;
  10. }
  11. public void setPassword(String password) {
  12.     this.password = password;
  13. }
  14. public String getUsername() {
  15.     return username;
  16. }
  17. public void setUsername(String username) {
  18.     this.username = username;
  19. }
  20. private boolean isInvalid(String value) {
  21.     return (value == null || value.length() == 0);
  22. }
  23. public String execute(){
  24.         System.out.println(username);
  25.         System.out.println(password);
  26.          if (isInvalid(getUsername()))
  27.                 return INPUT;
  28.             if (isInvalid(getPassword()))
  29.                 return INPUT;
  30.     if(this.getUsername().equals(“yuewei”)&& this.getPassword().equals(“yuewei”)){
  31.         ActionContext.getContext().getSession().put(Constants.USER_SESSION,getUsername());
  32.         ActionContext.getContext().getSession().put(Constants.PASS,getPassword());
  33.         return ”success”;
  34.     }
  35.     return ”error”;
  36. }
  37. }

 

ShowAction

  1. package com.ywjava.action;
  2. import com.opensymphony.xwork2.ActionSupport;
  3. public class ShowAction extends ActionSupport {
  4.  public String execute() {
  5.   return ”success”;
  6.  }
  7. }

 

三、拦截器

  1. package com.ywjava.interceptot;
  2. import java.util.Map;
  3. import com.opensymphony.xwork2.Action;
  4. import com.opensymphony.xwork2.ActionContext;
  5. import com.opensymphony.xwork2.ActionInvocation;
  6. import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
  7. import com.ywjava.utils.Constants;
  8. public class LoginInterceptor extends AbstractInterceptor {
  9.     @Override
  10.     public String intercept(ActionInvocation invocation) throws Exception {
  11.         // 取得请求相关的ActionContext实例
  12.         ActionContext ctx = invocation.getInvocationContext();
  13.         Map session = ctx.getSession();
  14.         String user = (String) session.get(Constants.USER_SESSION);
  15.         // 如果没有登陆,或者登陆所有的用户名不是yuewei,都返回重新登陆
  16.         if (user != null && user.equals(“yuewei”)) {
  17.             System.out.println(“test”);
  18.             return invocation.invoke();
  19.         }
  20.         ctx.put(“tip”, ”你还没有登录”);
  21.         return Action.LOGIN;
  22.     }
  23. }

 

四 struts.xml

  1. <?xml version=”1.0″ encoding=”UTF-8″?>
  2. <!DOCTYPE struts PUBLIC
  3.     ”-//Apache Software Foundation//DTD Struts Configuration 2.1//EN”
  4.     ”http://struts.apache.org/dtds/struts-2.1.dtd”>
  5. <struts>
  6.     <package name=”authority” extends=”struts-default”>
  7.         <!– 定义一个拦截器 –>
  8.         <interceptors>
  9.             <interceptor name=”authority”
  10.                 class=”com.ywjava.interceptot.LoginInterceptor”>
  11.             </interceptor>
  12.             <!– 拦截器栈 –>
  13.             <interceptor-stack name=”mydefault”>
  14.                 <interceptor-ref name=”defaultStack” />
  15.                 <interceptor-ref name=”authority” />
  16.             </interceptor-stack>
  17.         </interceptors>
  18.         <!– 定义全局Result –>
  19.         <global-results>
  20.             <!– 当返回login视图名时,转入/login.jsp页面 –>
  21.             <result name=”login”>/login.jsp</result>
  22.         </global-results>
  23.         <action name=”loginform”
  24.             class=”com.ywjava.action.LoginFormAction”>
  25.             <result name=”success”>/login.jsp</result>
  26.         </action>
  27.         <action name=”login” class=”com.ywjava.action.LoginAction”>
  28.             <result name=”success”>/welcome.jsp</result>
  29.             <result name=”error”>/login.jsp</result>
  30.             <result name=”input”>/login.jsp</result>
  31.         </action>
  32.         <action name=”show” class=”com.ywjava.action.ShowAction”>
  33.             <result name=”success”>/show.jsp</result>
  34.             <!– 使用此拦截器 –>
  35.             <interceptor-ref name=”mydefault” />
  36.         </action>
  37.     </package>
  38. </struts>
  39. http://blog.csdn.net/java_cxrs/article/details/5514340
  40. Struts2拦截器的使用 (详解)

    如何使用struts2拦截器,或者自定义拦截器。特别注意,在使用拦截器的时候,在Action里面必须最后一定要引用struts2自带的拦截器缺省堆栈defaultStack,如下(这里我是引用了struts2自带的checkbox拦截器):
    <interceptor-ref name=”checkbox”>
    <param name=”uncheckedValue”>0</param>
    < /interceptor-ref>
    <interceptor-ref name=”defaultStack”/>(必须加,否则出错)

    也可以改为对全局Action设置自己需要的拦截器,如下:

    在struts.xml里面定义全局的配置设置
    <package name=”struts-shop” extends=”struts-default”>
    <interceptors>
    <interceptor-stack name=”myStack“>
    <interceptor-ref name=”checkbox”>
    <param name=”uncheckedValue”>0</param>
    </interceptor-ref>
    <interceptor-ref name=”defaultStack”/>
    </interceptor-stack>
    </interceptors>
    <default-interceptor-ref name=”myStack”/>(这句是设置所有Action自动调用的拦截器堆栈)
      </package>

    struts-action.xml里面配置Action如下:
    <package name=”LogonAdmin” extends=”struts-shop”>(这里扩展struts.xml里面定义的配置就可以了)
    <action name=”logon”>
    <result>/jsp/smeishop/admin/index.jsp</result>
    <result name=”error”>/jsp/smeishop/admin/logon.jsp</result>
    <result name=”input”>/jsp/smeishop/admin/logon.jsp</result>
    </action>
    <action name=”logout”>
    <result>/jsp/smeishop/admin/logon.jsp</result>
    </action>
    </package>

    你的拦截器可以正常工作了!!HOHO

    以下是参考资料

    struts2自带的配置及其拦截器配置
    Struts2 拦截器 [Interceptor]

    拦截器的工作原理如上图,每一个Action请求都包装在一系列的拦截器的内部。拦截器可以在Action执行直线做相似的操作也可以在Action执行直后做回收操作。

     

    每一个Action既可以将操作转交给下面的拦截器,Action也可以直接退出操作返回客户既定的画面。

     

    如何自定义一个拦截器?

    自定义一个拦截器需要三步:

    1 自定义一个实现Interceptor接口(或者继承自AbstractInterceptor)的类。


    2 在strutx.xml中注册上一步中定义的拦截器。

    3 在需要使用的Action中引用上述定义的拦截器,为了方便也可将拦截器定义为默认的拦截器,这样在不加特殊声明的情况下所有的Action都被这个拦截器拦截。

     

    Interceptor接口声明了三个方法:

     

    public interface Interceptor extends Serializable {

     

        void destroy();

     

        void init();

     

        String intercept(ActionInvocation invocation) throws Exception;

    }

     

    Init方法在拦截器类被创建之后,在对Action镜像拦截之前调用,相当于一个post-constructor方法,使用这个方法可以给拦截器类做必要的初始话操作。

     

    Destroy方法在拦截器被垃圾回收之前调用,用来回收init方法初始化的资源。

     

    Intercept是拦截器的主要拦截方法,如果需要调用后续的Action或者拦截器,只需要在该方法中调用invocation.invoke()方法即可,在该方法调用的前后可以插入Action调用前后拦截器需要做的方法。如果不需要调用后续的方法,则返回一个String类型的对象即可,例如Action.SUCCESS。

    另外AbstractInterceptor提供了一个简单的Interceptor的实现,这个实现为:

    public abstract class AbstractInterceptor implements Interceptor {

     

         public void init() {

        }

       

        public void destroy() {

        }

     

     

        public abstract String intercept(ActionInvocation invocation) throws Exception;

    }

    在不需要编写init和destroy方法的时候,只需要从AbstractInterceptor继承而来,实现intercept方法即可。

     

    我们尝试编写一个Session过滤用的拦截器,该拦截器查看用户Session中是否存在特定的属性(LOGIN属性)如果不存在,中止后续操作定位到LOGIN,否则执行原定操作,代码为:

    public class CheckLoginInterceptor extends AbstractInterceptor {

        public static final String LOGIN_KEY = “LOGIN”;

        public static final String LOGIN_PAGE = “global.login”;

     

        public String intercept(ActionInvocation actionInvocation) throws Exception {

     

            System.out.println(“begin check login interceptor!”);

            // 对LoginAction不做该项拦截

            Object action = actionInvocation.getAction();

            if (action instanceof LoginAction) {

                System.out.println(“exit check login, because this is login action.”);

                return actionInvocation.invoke();

            }

     

            // 确认Session中是否存在LOGIN

            Map session = actionInvocation.getInvocationContext().getSession();

            String login = (String) session.get(LOGIN_KEY);

            if (login != null && login.length() > 0) {

                // 存在的情况下进行后续操作。

                System.out.println(“already login!”);

                return actionInvocation.invoke();

            } else {

                // 否则终止后续操作,返回LOGIN

                System.out.println(“no login, forward login page!”);

                return LOGIN_PAGE;

            }

        }

    }

     

    注册拦截器

    <interceptors>

                <interceptor

    name=”login” 

    class=”com.jpleasure.teamware.util.CheckLoginInterceptor”/>

                <interceptor-stack name=”teamwareStack”>

                    <interceptor-ref name=”login”/>

                    <interceptor-ref name=”defaultStack”/>

                </interceptor-stack>

    </interceptors>

     

    将上述拦截器设定为默认拦截器:

    <default-interceptor-ref name=”teamwareStack”/>

    这样在后续同一个package内部的所有Action执行之前都会被login拦截。

     

     

    Struts2(XWork)提供的拦截器的功能说明:

     

    拦截器 名字 说明
    Alias Interceptor alias 在不同请求之间将请求参数在不同名字件转换,请求内容不变
    Chaining Interceptor chain 让前一个Action的属性可以被后一个Action访问,现在和chain类型的result(<result type=”chain”>)结合使用。
    Checkbox Interceptor checkbox 添加了checkbox自动处理代码,将没有选中的checkbox的内容设定为false,而html默认情况下不提交没有选中的checkbox
    Cookies Interceptor cookies 使用配置的name,value来是指cookies
    Conversion Error Interceptor conversionError 将错误从ActionContext中添加到Action的属性字段中。
    Create Session Interceptor createSession 自动的创建HttpSession,用来为需要使用到HttpSession的拦截器服务。
    Debugging Interceptor debugging 提供不同的调试用的页面来展现内部的数据状况。
    Execute and Wait Interceptor execAndWait 在后台执行Action,同时将用户带到一个中间的等待页面。
    Exception Interceptor exception 将异常定位到一个画面
    File Upload Interceptor fileUpload 提供文件上传功能
    I18n Interceptor i18n 记录用户选择的locale
    Logger Interceptor logger 输出Action的名字
    Message Store Interceptor store 存储或者访问实现ValidationAware接口的Action类出现的消息,错误,字段错误等。
    Model Driven Interceptor model-driven 如果一个类实现了ModelDriven,将getModel得到的结果放在Value Stack中。
    Scoped Model Driven scoped-model-driven 如果一个Action实现了ScopedModelDriven,则这个拦截器会从相应的Scope中取出model调用Action的setModel方法将其放入Action内部。
    Parameters Interceptor params 将请求中的参数设置到Action中去。
    Prepare Interceptor prepare 如果Acton实现了Preparable,则该拦截器调用Action类的prepare方法。
    Scope Interceptor scope Action状态存入session和application的简单方法。
    Servlet Config Interceptor servletConfig 提供访问HttpServletRequest和HttpServletResponse的方法,以Map的方式访问。
    Static Parameters Interceptor staticParams struts.xml文件中将<action>中的<param>中的内容设置到对应的Action中。
    Roles Interceptor roles 确定用户是否具有JAAS指定的Role,否则不予执行。
    Timer Interceptor timer 输出Action执行的时间
    Token Interceptor token 通过Token来避免双击
    Token Session Interceptor tokenSession Token Interceptor一样,不过双击的时候把请求的数据存储在Session
    Validation Interceptor validation 使用action-validation.xml文件中定义的内容校验提交的数据。
    Workflow Interceptor workflow 调用Action的validate方法,一旦有错误返回,重新定位到INPUT画面
    Parameter Filter Interceptor N/A 从参数列表中删除不必要的参数
    Profiling Interceptor profiling 通过参数激活profile

     

    注册并引用Interceptor

    <package name=”default” extends=”struts-default”>

       <interceptors>

           <interceptor name=”timer”/>

           <interceptor name=”logger”/>

       </interceptors>

     

       <action name=”login”>

            <interceptor-ref name=”timer”/>

            <interceptor-ref name=”logger”/>

            <result name=”input”>login.jsp</result>

            <result name=”success”

                type=”redirect-action”>/secure/home</result>

       </action>

    </package>

     

    可以将多个拦截器合并在一起作为一个堆栈调用,当一个拦截器堆栈被附加到一个Action的时候,要想Action执行,必须执行拦截器堆栈中的每一个拦截器。

    <package name=”default” extends=”struts-default”>

       <interceptors>

            <interceptor name=”timer”/>

            <interceptor name=”logger”/>

            <interceptor-stack name=”myStack”>

               <interceptor-ref name=”timer”/>

               <interceptor-ref name=”logger”/>

            </interceptor-stack>

        </interceptors>

     

        <action name=”login”>

             <interceptor-ref name=”myStack”/>

             <result name=”input”>login.jsp</result>

             <result name=”success”

                 type=”redirect-action”>/secure/home</result>

        </action>

    </package>

     

    上述说明的拦截器在默认的Struts2应用中,根据惯例配置了若干个拦截器堆栈,详细情参看struts-default.xml

    其中有一个拦截器堆栈比较特殊,他会应用在默认的每一个Action上。

    <interceptor-stack name=”defaultStack”>

        <interceptor-ref name=”exception”/>

        <interceptor-ref name=”alias”/>

        <interceptor-ref name=”servletConfig”/>

        <interceptor-ref name=”prepare”/>

        <interceptor-ref name=”i18n”/>

        <interceptor-ref name=”chain”/>

        <interceptor-ref name=”debugging”/>

        <interceptor-ref name=”profiling”/>

        <interceptor-ref name=”scopedModelDriven”/>

        <interceptor-ref name=”modelDriven”/>

        <interceptor-ref name=”fileUpload”/>

        <interceptor-ref name=”checkbox”/>

        <interceptor-ref name=”staticParams”/>

        <interceptor-ref name=”params”>

          <param name=”excludeParams”>dojo”..*</param>

        </interceptor-ref>

        <interceptor-ref name=”conversionError”/>

        <interceptor-ref name=”validation”>

            <param name=”excludeMethods”>input,back,cancel,browse</param>

        </interceptor-ref>

        <interceptor-ref name=”workflow”>

            <param name=”excludeMethods”>input,back,cancel,browse</param>

        </interceptor-ref>

    </interceptor-stack>

     

    每一个拦截器都可以配置参数,有两种方式配置参数,一是针对每一个拦截器定义参数,二是针对一个拦截器堆栈统一定义所有的参数,例如:

    <interceptor-ref name=”validation”>

     <param name=”excludeMethods”>myValidationExcudeMethod</param>

    </interceptor-ref>

    <interceptor-ref name=”workflow”>

     <param name=”excludeMethods”>myWorkflowExcludeMethod</param>

    </interceptor-ref>

    或者

    <interceptor-ref name=”defaultStack”>

        <param name=”validation.excludeMethods”>myValidationExcludeMethod</param>

        <param name=”workflow.excludeMethods”>myWorkflowExcludeMethod</param>

    </interceptor-ref>

     

    每一个拦截器都有两个默认的参数:

    excludeMethods – 过滤掉不使用拦截器的方法和

    includeMethods – 使用拦截器的方法。

     

    需要说明的几点:

    1 拦截器执行的顺序按照定义的顺序执行,例如:

    <interceptor-stack name=”xaStack”>

     <interceptor-ref name=”thisWillRunFirstInterceptor”/>

     <interceptor-ref name=”thisWillRunNextInterceptor”/>

     <interceptor-ref name=”followedByThisInterceptor”/>

     <interceptor-ref name=”thisWillRunLastInterceptor”/>

    </interceptor-stack>

    的执行顺序为:

    thisWillRunFirstInterceptor

     thisWillRunNextInterceptor

        followedByThisInterceptor

          thisWillRunLastInterceptor

            MyAction1

            MyAction2 (chain)

            MyPreResultListener

            MyResult (result)

          thisWillRunLastInterceptor

        followedByThisInterceptor

     thisWillRunNextInterceptor

    thisWillRunFirstInterceptor

     

    2 使用默认拦截器配置每个Action都需要的拦截器堆栈,例如:

    <action name=”login” class=”tutorial.Login”>

         <interceptor-ref name=”timer”/>

         <interceptor-ref name=”logger”/>

         <interceptor-ref name=”default-stack”/>

     

         <result name=”input”>login.jsp</result>

         <result type=”redirect-action”>/secure/home</result>

    </action>

    可以按照如下的方式定义:

    <interceptors>

         <interceptor-stack name=”myStack”>

            <interceptor-ref name=”timer”/>

            <interceptor-ref name=”logger”/>

            <interceptor-ref name=”default-stack”/>

         </interceptor-stack>

    </interceptors>

     

    <default-interceptor-ref name=”myStack”/>

     

    <action name=”login” class=”tutorial.Login”>

           <result name=”input”>login.jsp</result>

           <result type=”redirect-action”>/secure/home</result>

    </action>

     

    3 如何访问HttpServletRequest,HttpServletResponse或者HttpSession

    有两种方法可以达到效果,使用ActionContext

    Map attibutes = ActionContext.getContext().getSession();

    或者实现相应的接口:

    HttpSession            SessionAware

    HttpServletRequest     ServletRequestAware

    HttpServletResponse    ServletResponseAware

    Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1820668