以下是一个 Struts2 拦截器的完整示例,该拦截器用于记录每个请求的处理时间:
一、创建拦截器类
package com.example.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import java.util.Date;
public class TimeLoggingInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
long startTime = new Date().getTime();
String result = invocation.invoke();
long endTime = new Date().getTime();
long duration = endTime - startTime;
System.out.println("Action execution time: " + duration + " milliseconds.");
return result;
}
}
二、配置 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="default" extends="struts-default">
<interceptors>
<interceptor name="timeLoggingInterceptor" class="com.example.interceptor.TimeLoggingInterceptor"/>
</interceptors>
<action name="exampleAction" class="com.example.action.ExampleAction">
<interceptor-ref name="timeLoggingInterceptor"/>
<result>/success.jsp</result>
</action>
</package>
</struts>
三、创建 Action 类
package com.example.action;
import com.opensymphony.xwork2.ActionSupport;
public class ExampleAction extends ActionSupport {
public String execute() {
// 模拟一些耗时的操作
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return SUCCESS;
}
}
四、创建视图页面 success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>成功页面</title>
</head>
<body>
操作成功!
</body>
</html>
在这个示例中,TimeLoggingInterceptor拦截器在 Action 执行前后记录时间,并计算出 Action 的执行时间并打印到控制台。当用户请求exampleAction时,该拦截器会记录请求的处理时间。
506



被折叠的 条评论
为什么被折叠?



