您的位置:首页 > 编程语言 > Java开发

Struts2---拦截器

2017-05-13 17:34 369 查看
定义一个拦截器:

第一步:

1.创建一个继承自AbstractInterceptor/Interceptor的类;

2.实现intercept方法(后者需要实现initial()和destroy()方法)。

第二步:

1.在XML文件中对拦截器进行注册;

2.在相应的Action中进行引用。



<%@ page language="java" import="java.util.*" contentType="text/html; charset=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>建立拦截器 计时Action运行时间</title>

</head>

<body>
<a href="TimeAction.action">点击开始计时---!</a>
</body>
</html>


package com.inteceptor;

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

public class TimeInterceptor extends AbstractInterceptor {

@Override
public String intercept(ActionInvocation invocation) throws Ex
4000
ception {
//执行之前
long start=System.currentTimeMillis();
//执行下一个拦截器  如果是最后一个拦截器就跳转到目标Action
String   result=  invocation.invoke();
long end =System.currentTimeMillis();
System.out.println("TimeAction执行的时间==="+(end-start)+"ms");
System.out.println("结果视图字符串:"+result);
return result;
//这个result字符串就是我们的结果视图   action中的方法执行后返回的字符串
}

}


<?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="default" namespace="/"  extends="struts-default">
<!-- 注册拦截器 -->
<interceptors>
<interceptor name="mytimer" class="com.inteceptor.TimeInterceptor"></interceptor>
</interceptors>

<action name="TimeAction" class="com.action.TimeAction">
<!-- 引用拦截器-->
<interceptor-ref name="mytimer"></interceptor-ref>
<result>/success.jsp</result>
</action>
</package>
</struts>


执行结果:::::

爱你的我!!

爱你的我!!

爱你的我!!

爱你的我!!

爱你的我!!

TimeAction执行的时间===102ms

结果视图字符串:success
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: