Posted on 2010-03-29 23:17
Gavin.lee 阅读(489)
评论(0) 编辑 收藏 所属分类:
SSH2 --Struts2
一、拦截器定义
拦截器,在AOP(Aspect-Oriented Programming)中用于在某个方法或字段被访问之前,进行拦截然后在之前或之后加入某些操作。拦截是AOP的一种实现策略。
在Webwork的中文文档的解释为——拦截器是动态拦截Action调用的对象。它提供了一种机制可以使开发者可以定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行。同时也是提供了一种可以提取action中可重用的部分的方式。
谈到拦截器,还有一个词大家应该知道——拦截器链(Interceptor Chain,在Struts 2中称为拦截器栈Interceptor Stack)。拦截器链就是将拦截器按一定的顺序联结成一条链。在访问被拦截的方法或字段时,拦截器链中的拦截器就会按其之前定义的顺序被调用。
二、拦截器的流程 访问: http://localhost:8080/interceptor1/test_interceptor.action
1.拦截器的触发页面

<%
@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>

<%
@ taglib prefix="s" uri="/struts-tags"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.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 action="test_interceptor">
<s:textfield name="username" label="username"></s:textfield>
<s:submit name="submit"></s:submit>
</s:form>
</body>
</html>

2.Struts2配置文件,拦截器的映射
<?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="interceptor1" extends="struts-default">

<!-- 定义拦截器 -->
<interceptors>
<interceptor name="myInterceptor" class="cn.edu.hdu.interceptor.MyInterceptor"></interceptor>
</interceptors>

<!-- 配置action -->
<action name="test_interceptor" class="cn.edu.hdu.action.Test_InterceptorAction">
<result name="success">/success.jsp</result>
<result name="input">/test.jsp</result>
<!-- 将声明好的拦截器插入action中 -->
<interceptor-ref name="myInterceptor" />
<interceptor-ref name="defaultStack" />
</action>
</package>
</struts>
3.拦截器MyInterceptor
package cn.edu.hdu.interceptor;

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


/** *//**
* 自定义拦截器
* @author gavin
* @date 2010-3-29
*/

public class MyInterceptor implements Interceptor
{

/** *//**
*
*/
private static final long serialVersionUID = -4855835386612768133L;


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


public void init()
{
System.out.println("拦截器已经被加载");
}


public String intercept(ActionInvocation invocation) throws Exception
{
System.out.println("调用intercept方法");
// invocation.invoke()方法检查是否还有拦截器 有的话继续调用余下的拦截器 没有了 执行action的业务逻辑
String result = invocation.invoke();
return result;
}
}

4.通过拦截器后进入Action
package cn.edu.hdu.action;

import com.opensymphony.xwork2.ActionSupport;


public class Test_InterceptorAction extends ActionSupport
{

/** *//**
*
*/
private static final long serialVersionUID = 5138320466369666402L;
private String username;


public String getUsername()
{
return username;
}


public void setUsername(String username)
{
this.username = username;
}


public String execute() throws Exception
{
return SUCCESS;
}


public String test() throws Exception
{
System.out.println("此时所有拦截器完毕,已经调用了action中的test方法");
return SUCCESS;
}

}

5.通过Action处理后的视图页面

<%
@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'success.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>
去看看控制台吧
</body>
</html>

三、Struts2默认的拦截器
<!--struts2中拦截器的定义-->
<interceptors>
<!--实现在不同请求中相似参数别名的准换-->
<interceptor name="alias" class="com.opensymphony.xwork2.interceptor.AliasInterceptor"/>
<!--与Spring整合时自动装配的拦截器-->
<interceptor name="autowiring" class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor"/>
<!--构建一个action链,使当前action可以访问前一个action,与<result-type="chain" />配合使用-->
<interceptor name="chain" class="com.opensymphony.xwork2.interceptor.ChainingInterceptor"/>
<!--负责类型转换的拦截器-->
<interceptor name="conversionError" class="org.apache.struts2.interceptor.StrutsConversionErrorInterceptor"/>
<!--使用配置的name,value来是指cookies -->
<interceptor name="cookie" class="org.apache.struts2.interceptor.CookieInterceptor"/>
<!--负责创建httpSession-->
<interceptor name="createSession" class="org.apache.struts2.interceptor.CreateSessionInterceptor" />
<!--输出调试信息-->
<interceptor name="debugging" class="org.apache.struts2.interceptor.debugging.DebuggingInterceptor" />
<!--扩展引用-->
<interceptor name="externalRef" class="com.opensymphony.xwork2.interceptor.ExternalReferencesInterceptor"/>
<!--后台执行action负责发送等待画面给用户-->
<interceptor name="execAndWait" class="org.apache.struts2.interceptor.ExecuteAndWaitInterceptor"/>
<!--异常处理-->
<interceptor name="exception" class="com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor"/>
<!--文件上传,解析表单域的内容-->
<interceptor name="fileUpload" class="org.apache.struts2.interceptor.FileUploadInterceptor"/>
<!--支持国际化-->
<interceptor name="i18n" class="com.opensymphony.xwork2.interceptor.I18nInterceptor"/>
<!--日志记录-->
<interceptor name="logger" class="com.opensymphony.xwork2.interceptor.LoggingInterceptor"/>
<!--模型拦截器,当action实现了ModelDriven接口时,负责把getModel的结果放入valueStack中-->
<interceptor name="modelDriven" class="com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor"/>
<!--有生命周期的ModelDriven-->
<interceptor name="scopedModelDriven" class="com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor"/>
<!--负责解析请求中的参数,并赋值给action中对应的属性-->
<interceptor name="params" class="com.opensymphony.xwork2.interceptor.ParametersInterceptor"/>
<!--实现该Preparable接口的action,会调用拦截器的prepare方法-->
<interceptor name="prepare" class="com.opensymphony.xwork2.interceptor.PrepareInterceptor"/>
<!--负责将action 标签下的param参数值传递给action实例-->
<interceptor name="staticParams" class="com.opensymphony.xwork2.interceptor.StaticParametersInterceptor"/>
<!--范围转换-->
<interceptor name="scope" class="org.apache.struts2.interceptor.ScopeInterceptor"/>
<!--用于访问Servlet API-->
<interceptor name="servletConfig" class="org.apache.struts2.interceptor.ServletConfigInterceptor"/>
<interceptor name="sessionAutowiring" class="org.apache.struts2.spring.interceptor.SessionContextAutowiringInterceptor"/>
<!--输出action执行时间-->
<interceptor name="timer" class="com.opensymphony.xwork2.interceptor.TimerInterceptor"/>
<!--防止表单重复提交-->
<interceptor name="token" class="org.apache.struts2.interceptor.TokenInterceptor"/>
<!--与token拦截器相似,只是把token保存到HttpSession-->
<interceptor name="tokenSession" class="org.apache.struts2.interceptor.TokenSessionStoreInterceptor"/>
<!--负责表单字段的验证 *-validation.xml-->
<interceptor name="validation" class="org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor"/>
<!--负责执行action的validate()-->
<interceptor name="workflow" class="com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor"/>
<!--存储和重新获取Action 消息/错误/字段错误为Action,实现ValidationAware接口到seesion-->
<interceptor name="store" class="org.apache.struts2.interceptor.MessageStoreInterceptor" />
<!--添加自动checkbox处理代码,这样检探测checkbox和添加它作为一个参数使用默认值(通常’false’).使用一个指定名字隐藏字段探测没提交的checkbox-->
<interceptor name="checkbox" class="org.apache.struts2.interceptor.CheckboxInterceptor" />
<interceptor name="profiling" class="org.apache.struts2.interceptor.ProfilingActivationInterceptor" />
<!--JAAS服务拦截器-->
<interceptor name="roles" class="org.apache.struts2.interceptor.RolesInterceptor" />
<!-- 一个基本的拦截器栈 -->
<interceptor-stack name="basicStack">
<interceptor-ref name="exception"/>
<interceptor-ref name="servletConfig"/>
<interceptor-ref name="prepare"/>
<interceptor-ref name="checkbox"/>
<interceptor-ref name="params"/>
<interceptor-ref name="conversionError"/>
</interceptor-stack>
<!-- 简单的validtion和webflow栈 -->
<interceptor-stack name="validationWorkflowStack">
<interceptor-ref name="basicStack"/>
<interceptor-ref name="validation"/>
<interceptor-ref name="workflow"/>
</interceptor-stack>
<!-- 文件上传的拦截器栈 -->
<interceptor-stack name="fileUploadStack">
<interceptor-ref name="fileUpload"/>
<interceptor-ref name="basicStack"/>
</interceptor-stack>
<!-- model-driven 栈 -->
<interceptor-stack name="modelDrivenStack">
<interceptor-ref name="modelDriven"/>
<interceptor-ref name="basicStack"/>
</interceptor-stack>
<!-- action链的拦截器栈 -->
<interceptor-stack name="chainStack">
<interceptor-ref name="chain"/>
<interceptor-ref name="basicStack"/>
</interceptor-stack>
<!-- i18n 拦截器栈 -->
<interceptor-stack name="i18nStack">
<interceptor-ref name="i18n"/>
<interceptor-ref name="basicStack"/>
</interceptor-stack>
<!-- 结合preparable和ModenDriven拦截器-->
<interceptor-stack name="paramsPrepareParamsStack">
<interceptor-ref name="exception"/>
<interceptor-ref name="alias"/>
<interceptor-ref name="params"/>
<interceptor-ref name="servletConfig"/>
<interceptor-ref name="prepare"/>
<interceptor-ref name="i18n"/>
<interceptor-ref name="chain"/>
<interceptor-ref name="modelDriven"/>
<interceptor-ref name="fileUpload"/>
<interceptor-ref name="checkbox"/>
<interceptor-ref name="staticParams"/>
<interceptor-ref name="params"/>
<interceptor-ref name="conversionError"/>
<interceptor-ref name="validation">
<param name="excludeMethods">input,back,cancel</param>
</interceptor-ref>
<interceptor-ref name="workflow">
<param name="excludeMethods">input,back,cancel</param>
</interceptor-ref>
</interceptor-stack>
<!--定义默认的拦截器栈 -->
<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-stack name="completeStack">
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
<interceptor-stack name="executeAndWaitStack">
<interceptor-ref name="execAndWait">
<param name="excludeMethods">input,back,cancel</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="execAndWait">
<param name="excludeMethods">input,back,cancel</param>
</interceptor-ref>
</interceptor-stack>
<interceptor name="external-ref" class="com.opensymphony.xwork2.interceptor.ExternalReferencesInterceptor"/>
<interceptor name="model-driven" class="com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor"/>
<interceptor name="static-params" class="com.opensymphony.xwork2.interceptor.StaticParametersInterceptor"/>
<interceptor name="scoped-model-driven" class="com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor"/>
<interceptor name="servlet-config" class="org.apache.struts2.interceptor.ServletConfigInterceptor"/>
<interceptor name="token-session" class="org.apache.struts2.interceptor.TokenSessionStoreInterceptor"/>
</interceptors>
<!--定义默认拦截器为"defaultStack"-->
<default-interceptor-ref name="defaultStack"/>