Struts2 拦截器demo
计算Action执行时间
思路:执行之后的时间 - 执行之前的时间 = 执行Action消耗的时间
实现步骤:创建拦截器
在配置文件中定义拦截器并引用它
访问路径:http://localhost:8080/struts-timerIntercept/
index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>计算执行Action花费的时间</title> </head> <body> <a href="timer">访问Action并计算执行Action花费的时间</a> </body> </html>
TimerAction.java
package com.action; import com.opensymphony.xwork2.ActionSupport; public class TimerAction extends ActionSupport { @Override public String execute() throws Exception { for(int i=0; i<1000; i++){ System.out.println("wow!!!"); } return SUCCESS; } }
TimerInterceptor.java
package com.interceptor; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; /* *计算执行Action花费的时间 */ public class TimerInterceptor extends AbstractInterceptor { @Override public String intercept(ActionInvocation invocation) throws Exception { //1.执行Action之前 long start = System.currentTimeMillis(); //2.执行下一个拦截器,如果已经是最后一个拦截器,则执行目标Action String reslut = invocation.invoke(); //3.执行Action之后 long end = System.currentTimeMillis(); System.out.println("执行Action花费的时间: " + (end - start) + "ms"); return reslut; } }
struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <package name="default" namespace="/" extends="struts-default"> <!-- 注册拦截器 --> <interceptors> <interceptor name="mytimer" class="com.interceptor.TimerInterceptor"></interceptor> </interceptors> <action name="timer" class="com.action.TimerAction"> <result>/success.jsp</result> <!-- 引用拦截器 --> <interceptor-ref name="mytimer"></interceptor-ref> </action> </package> </struts>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>Struts Blank</display-name> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
目录结构: