首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

struts2详解(3)->>拦截器

2012-12-18 
struts2详解(三)----拦截器struts2详解(三)----拦截器??拦截器介绍:??? 1、使用拦截器可以实现横切功能

struts2详解(三)---->>拦截器

struts2详解(三)---->>拦截器

?

?拦截器介绍:

??? 1、使用拦截器可以实现横切功能并使这些实现相对action甚至Struts2框架保持独立。
??? 2、可以实现和使用自己所需的特性且不用修改框架的底层代码。
??? 3、使用拦截器可以达到以下目的:


??????????在调用Action之前,提供预处理逻辑
????????? 与Action进行交互,提供执行信息,比如设置请求中的参数
???????? ?在调用Action之后,提供后处理逻辑
????????? 修改返回的结果,进而修改呈现给用户的内容
????????? 捕获异常从而替换可执行的处理过程或返回一个不同结果

?

?下面就通过一个小的案例来:

?

?index.jsp

?

<body>       <a href="csdn/uploads.action?name='z_xiaofei168'">查看</a></body>

?

?UserAction.java

?

?

package cn.csdn.struts2.action;import com.opensymphony.xwork2.ActionSupport;public class UserAction extends ActionSupport {/** * @author z_xiaofei168 */private static final long serialVersionUID = 1L;private String name;public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String execute() throws Exception {System.out.println("你传的值是:"+name);return SUCCESS;}}

?

? MyDateInterceptor.java

?

?

package cn.csdn.strut2.interceptors;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.Interceptor;public class MyDateInterceptor implements Interceptor{/** * @author z_xiaofei168 */private static final long serialVersionUID = 1L;public void destroy() {System.out.println("struts2框架关闭时销毁......");}public void init() {System.out.println("struts2框架加载时启动......");}public String intercept(ActionInvocation ai) throws Exception {System.out.println("拦截器执行......");long beforetime = System.currentTimeMillis();String obj = ai.invoke();long aftertime = System.currentTimeMillis();System.out.println("执行的时间是:"+(aftertime-beforetime)+" ms");return obj;}}

?

?? 备注:

???????? Interceptor接口与AbstractInterceptor
???????? init() 方法用来初始化拦截器
???????? destroy()方法为拦截器提供清理
???????? intercept()方法为拦截器处理业务规则
?????? ?其中,init()和destroy()仅在Struts2初始化时和框架关闭时分别执行一次,而intercept()会在每次请求中都会被调用,所以拦截器需要线程安全,尤其是intercept()方法。

?

? 配置文件:struts.xml

?

?

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN""http://struts.apache.org/dtds/struts-2.1.7.dtd"><struts><package name="csdn" extends="struts-default" namespace="/csdn"><!-- 声明自定义拦截器 --><interceptors><interceptor name="myTimer"/><!-- 自己定义的拦截器栈 --><interceptor-stack name="mystack"><!-- 使用struts2自带拦截器--><interceptor-ref name="timer" /><!-- 使用自定义的拦截器 --><interceptor-ref name="myTimer" /><!-- 引用struts2中默认的拦截器栈 --><interceptor-ref name="defaultStack" /></interceptor-stack></interceptors><!-- 使用自己定义的拦截器栈作为默认的拦截器栈 --><default-interceptor-ref name="mystack" /><!-- 全局结果集 --><global-results><result name="input">/index.jsp</result></global-results><!-- action --><action name="upload" src="/img/2012/11/09/1340372754.png" width="675" alt="struts2详解(3)->>拦截器">

?

?? 当你点击“查看”时,运行结果如下图所示:

?

?struts2详解(3)->>拦截器

?

?

?比较运行两次结果的不同

?

?

?

?

?

热点排行