歡迎您光臨本站 註冊首頁

10分鐘學懂Struts 2.0 攔截器

←手機掃碼閱讀     火星人 @ 2014-03-10 , reply:0

簡介

在Struts 2.0 中的攔截器,要實現com.opensymphony.xwork2.interceptor.Interceptor介面,在struts.xml中配置.可以用攔截器來完成調用Action業務邏輯之前的預處理或是之後的善後處理.還可以通過配置多個攔截器來滿足action需求.

Interceptor stack是由多個攔截器組成的攔截器組,在攔截器組中可以對每一個攔截器映射.所有進行配置攔截器時,不必對每一個攔截器進行配置,而只需對interceptor stack進行配置即可.在struts 2中默認配置了一個全局interceptor stack,包括Exception Interceptor、Validation Interceptor等.

實例

在這個實例當中,我將配置一個時間攔截器,用來統計每個action的請求時間.

package interceptor;

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

*author by
http://www.bt285.cn http://www.5a520.cn
*/

public class ActionTimer implements Interceptor{
public String intercept(ActionInvocation next) throws Exception {

long t1 = System.currentTimeMillis();
String s
= next.invoke();
long t2 = System.currentTimeMillis();
System.out.println(
"Action " next.getAction().getClass().getName() " took " (t2-t1) " millisecs");
return s;
}


public void init() {

}

public void destroy() {
}

}

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="interceptor" extends="struts-default">
<interceptors>
<interceptor name="actiontimer"
class
="interceptor.ActionTimer" />

<interceptor-stack name="demostack">

<interceptor-ref name="defaultStack" />
<interceptor-ref name="actiontimer" />
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="demostack" />
<action name="InterceptorDemo"
class
="interceptor.action.InterceptorDemo">

<result>http://www.bt285.cn /interceptor/interceptordemo.jsp</result>
</action>
</package>

</struts>

interceptordemo.jsp:

<html>
<head>

</head>

<body>
</body>
</html>


[火星人 ] 10分鐘學懂Struts 2.0 攔截器已經有579次圍觀

http://coctec.com/docs/java/show-post-61680.html