随笔 - 117  文章 - 72  trackbacks - 0

声明:原创作品(标有[原]字样)转载时请注明出处,谢谢。

常用链接

常用设置
常用软件
常用命令
 

订阅

订阅

留言簿(7)

随笔分类(130)

随笔档案(123)

搜索

  •  

积分与排名

  • 积分 - 152521
  • 排名 - 390

最新评论

[标题]:[原]Struts2-拦截器
[时间]:2009-7-31
[摘要]:Struts Interceptor
[关键字]:浪曦视频,Struts2应用开发系列,WebWork,Apache,Interceptor,拦截器,动态代理,Java,Proxy
[环境]:struts-2.1.6、JDK6、MyEclipse7、Tomcat6
[作者]:Winty (wintys@gmail.com) http://www.blogjava.net/wintys

[正文]:
1、知识点
a.Struts2拦截器Interceptor
    Struts2拦截器的根接口为: xwork-2.1.2.jar/com.opensymphony.xwork2.interceptor.Interceptor
    自定义的拦截器可以实现Interceptor接口。com.opensymphony.xwork2.interceptor.AbstractInterceptor 提供了对Interceptor的默认实现,自定义拦截器也可以继承AbstractInterceptor。

b.定义拦截器
/StrutsHelloWorld/src/wintys/struts2/interceptor/MyInterceptor.java:
package wintys.struts2.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * 拦截器、Interceptor
 *
 * http://www.blogjava.net/wintys
 * @author Winty (wintys@gmail.com)
 * @version 2009-07-30
 *
 */
@SuppressWarnings("serial")
public class MyInterceptor implements Interceptor {

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        
        System.out.println("before...");
        
        String result = invocation.invoke();
        
        System.out.println("after...");
        
        return result;
    }

    @Override
    public void destroy() {
        System.out.println("MyInterceptor destroy()...");
    }

    @Override
    public void init() {
        System.out.println("MyInterceptor init()...");
    }

}

c.在struts.xml中配置拦截器
<package name="MyStruts" extends="struts-default">
    <interceptors>
            <interceptor name="myInterceptor" class="wintys.struts2.interceptor.MyInterceptor" />

            <interceptor-stack name="myStack">
                <interceptor-ref name="myInterceptor"/>
                <interceptor-ref name="defaultStack"/>
            </interceptor-stack>
    </interceptors>
    ......
    <action name="intercept" class="wintys.struts2.interceptor.InterceptAction">
        <result name="success">/interceptor/output.jsp</result>
           <result name="input">/interceptor/input.jsp</result>
        <interceptor-ref name="myStack" />
    </action>
</package>

    defaultStack是Struts默认的拦截器。在action中手动引入interceptor后,就不会启用默认的interceptor,除非手动引入。所以要加上默认interceptor:<interceptor-ref name="defaultStack">。

    在input.jsp请求Action "intercept"时,在Action的execute()方法执行时,就会触发拦截器。

d.带参数的拦截器
    配置(在定义时给参数赋值):
    <interceptor name="myParamInterceptor" class="wintys.struts2.interceptor.MyParamInterceptor" >
        <param name="info">This is a param.</param>
    </interceptor>

    在自定义拦截器中实现代码(添加info属性、setter和getter):
/StrutsHelloWorld/src/wintys/struts2/interceptor/MyParamInterceptor.java
package wintys.struts2.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 带参数的拦截器、AbstractInterceptor
 *
 * http://www.blogjava.net/wintys
 * @author Winty (wintys@gmail.com)
 * @version 2009-07-30
 *
 */
@SuppressWarnings("serial")
public class MyParamInterceptor extends AbstractInterceptor {
    private String info;
    
    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        System.out.println("before2...");
        System.out.println("info:" + info);
        
        String result = invocation.invoke();
        
        System.out.println("after2...");
        
        return result;
    }

}

    在引用时给参数赋值,会覆盖定义时的赋值:
    <interceptor-ref name="myParamInterceptor">
        <param name="info">This is another param.</param>
    </interceptor-ref>


e.拦截器栈
    拦截器栈与拦截器具有同等地位,使用相同。拦截器栈可以再包含拦截器或拦截器栈。
<interceptors>
    <interceptor-stack name="myStack">
        <interceptor-ref name="myInterceptor" />
        <interceptor-ref name="defaultStack" />
    </interceptor>
</interceptors>

    拦截器栈中定义的多个拦截器执行顺序与拦截器配置顺序相同。同时,多个拦截器的执行流程如下: interceptorA begin => interceptorB begin => action => interceptorB end => interceptorA end


f.指定默认拦截器    
    Struts默认的拦截器是defaultStack,可以在struts.xml中使用如下配置重新指定默认拦截器:
<package>
    ......
    <default-interceptor-ref name="myStack" />
    ......
</package>


g.方法过滤拦截器MethodFilterInteceptor
    MethodFilterInteceptor可以选择需要过滤的方法,通过参数进行配置。实现MethodFilterInteceptor.doIntercept(),以提供拦截功能。
<action>
    <interceptor-ref name="myInterceptor">
        <param name="includeMethods">test,execute</param>
        <param name="excludeMethods">somemethod</param>
    </interceptor-ref>
</action>


f.PreResultListener
    可以在拦截器中添加PreResultListener,以实现特定功能。PreResultListener在业务方法(通常为execute)返回后(执行成功则返回"success"),页面视图呈现到客户端之前执行。

    public String intercept(ActionInvocation invocation) throws Exception {
        ......
        invocation.addPreResultListener(...);
        ......
    }


2、详细代码
/StrutsHelloWorld/src/wintys/struts2/interceptor/MyMethodFilterInterceptor.java:
package wintys.struts2.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
import com.opensymphony.xwork2.interceptor.PreResultListener;

/**
 * 选择性拦截方法的拦截器MethodFilterInterceptor、监听器PreResultListener
 *
 * http://www.blogjava.net/wintys
 * @author Winty (wintys@gmail.com)
 * @version 2009-07-30
 *
 */
@SuppressWarnings("serial")
public class MyMethodFilterInterceptor extends MethodFilterInterceptor {

    @Override
    protected String doIntercept(ActionInvocation invocation) throws Exception {
        System.out.println("MyMethodFilterInterceptor is running...");
        
        //添加监听器PreResultListener
        invocation.addPreResultListener(new PreResultListener(){
            public void beforeResult(ActionInvocation invocation, String resultCode){
                System.out.println("PreResultListener ..." + resultCode);
            }
            
        });
        
        String result = invocation.invoke();        
        
        return result;
    }

}


/StrutsHelloWorld/WebRoot/interceptor/input.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
  </head>
 
  <body>
  <s:form action="intercept">
      <s:textfield name="user" label="user" /><br/>
      <s:submit name="submit" label=" 提交  " />
  </s:form>
    
  </body>
</html>



/StrutsHelloWorld/src/wintys/struts2/interceptor/InterceptAction.java:
package wintys.struts2.interceptor;

import com.opensymphony.xwork2.ActionSupport;

/**
 *
 * @author Winty (wintys@gmail.com)
 * @version 2009-07-30
 * http://www.blogjava.net/wintys
 */
@SuppressWarnings("serial")
public class InterceptAction extends ActionSupport {
    private String user;

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }
    
    @Override
    public String execute() throws Exception {
        System.out.println("execute()...");
        
        return SUCCESS;
    }
    
    @Override
    public void validate() {
        System.out.println("validate()...");
        
        if(user == null || user.length() < 6){
            addFieldError("user", "invalid user");
        }
    }
}



/StrutsHelloWorld/WebRoot/interceptor/output.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'output.jsp' starting page</title>    
 </head>
 
  <body>
    <s:property value="user"/>
  </body>
</html>


/StrutsHelloWorld/src/struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <package name="MyStruts" extends="struts-default">
        <!-- 拦截器 -->
        <interceptors>
            <interceptor name="myInterceptor" class="wintys.struts2.interceptor.MyInterceptor" />
            <interceptor name="myParamInterceptor" class="wintys.struts2.interceptor.MyParamInterceptor" >
                <param name="info">This is a param.</param>
            </interceptor>
            <interceptor name="myMethodFilterInterceptor" class="wintys.struts2.interceptor.MyMethodFilterInterceptor">
                <param name="includeMethods">execute</param>
            </interceptor>
            
            <interceptor-stack name="myStack">
                <interceptor-ref name="myParamInterceptor">
                    <param name="info">This is another param.</param>
                </interceptor-ref>
                <interceptor-ref name="myInterceptor"/>
                <interceptor-ref name="myMethodFilterInterceptor"/>
                <interceptor-ref name="defaultStack"/>
            </interceptor-stack>
        </interceptors>
              
        <action name="intercept" class="wintys.struts2.interceptor.InterceptAction">
            <result name="success">/interceptor/output.jsp</result>
               <result name="input">/interceptor/input.jsp</result>
               <interceptor-ref name="myStack" />
        </action>
        
    </package>
</struts>

3、小例子:登录拦截
    登录拦截:拦截Action实现在输入信息之前必须登录,如果没有登录,则转到登录页面。

/StrutsHelloWorld/WebRoot/interceptor/login.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
  </head>
 
  <body>
  <s:form action="authentication">
    正确id:10000
      <s:textfield name="id" label="id" /><br/>
      <s:submit name="submit" label=" 提交  " />
  </s:form>
    
  </body>
</html>

Struts2中的Session可以脱离容器,以方便测试,对应于容器中的Session。

/StrutsHelloWorld/src/wintys/struts2/interceptor/AuthenticationAction.java:
package wintys.struts2.interceptor;

import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class AuthenticationAction extends ActionSupport {
    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
    
    @Override
    public String execute() throws Exception {
        
        if( id.equals("10000")){
            Map<String , Object> map = ActionContext.getContext().getSession();
            map.put("id", id);
            
            return SUCCESS;
        }
        else{
            addFieldError("id", "id error");
            
            return INPUT;
        }
    }
    
    @Override
    public void validate() {
        if(id == null || id.length() < 3)
            addFieldError("id", "invalid id");
    }
}


/StrutsHelloWorld/src/wintys/struts2/interceptor/AuthenticationInterceptor.java:
package wintys.struts2.interceptor;

import java.util.Map;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 认证拦截器:判断用户是否已登录
 *
 * http://www.blogjava.net/wintys
 * @author Winty (wintys@gmail.com)
 * @version 2009-07-30
 *
 */
@SuppressWarnings("serial")
public class AuthenticationInterceptor extends AbstractInterceptor {

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        System.out.println("AuthenticationInterceptor ...");
        
        Map<String , Object> map = invocation.getInvocationContext().getSession();
        
        Object id = map.get("id");
        if( id == null){
            return Action.LOGIN;
        }else{
            System.out.println("id" + id);
            
            return invocation.invoke();
        }
    }

}


struts.xml配置:
......
<package name="MyStruts" extends="struts-default">
        <!-- 拦截器 -->
        <interceptors>
            <interceptor name="authenticationInterceptor" class="wintys.struts2.interceptor.AuthenticationInterceptor"/>
            
            <interceptor-stack name="myStack">
                <interceptor-ref name="authenticationInterceptor"/>
                <interceptor-ref name="defaultStack"/>
            </interceptor-stack>
        </interceptors>
        
        <!-- 全局result -->
        <global-results>
            <result name="login" type="redirect">/interceptor/login.jsp</result>
        </global-results>
        
        <action name="intercept" class="wintys.struts2.interceptor.InterceptAction">
            <result name="success">/interceptor/output.jsp</result>
               <result name="input">/interceptor/input.jsp</result>
               <interceptor-ref name="myStack" />
        </action>
        <action name="authentication" class="wintys.struts2.interceptor.AuthenticationAction">
            <result name="success">/interceptor/input.jsp</result>
            <result name="input" type="dispatcher">/interceptor/login.jsp</result>
        </action>
        
</package>
......

[参考资料]:
    《浪曦视频之Struts2应用开发系列》

[附件]:
    源代码: http://www.blogjava.net/Files/wintys/struts_HelloWorld_Interceptor.zip
posted on 2009-08-01 00:21 天堂露珠 阅读(737) 评论(0)  编辑  收藏 所属分类: Struts

只有注册用户登录后才能发表评论。


网站导航: