1) Create a class that implements the Interceptor interface and implement the intercept() method
2) Configure the created interceptor in the struts.xml file. Make sure that this configuration appears at the top of the XML file within the <package> element
3) Test the interceptor with any URL that invokes a Struts2 action. Check the server console for output statements from the interceptor.
package info.icontraining.struts2;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class MyLoggingInterceptor implements Interceptor {
public void destroy() { }
public void init() { }
public String intercept(ActionInvocation invocation) throws Exception {
// pre-processing task
String className = invocation.getAction().getClass().getName();
long startTime = System.currentTimeMillis();
System.out.println("Before calling action: " + className);
// invoking the next interceptor or the action
String result = invocation.invoke();
// post-processing task
long endTime = System.currentTimeMillis();
System.out.println("After calling action: " + className
+ " Time taken: " + (endTime - startTime) + " ms");
return result;
}
}
2) Configure the created interceptor in the struts.xml file. Make sure that this configuration appears at the top of the XML file within the <package> element
...
<package name="myPackage" extends="struts-default">
<interceptors>
<interceptor name="myLogger"
class="info.icontraining.struts2.MyLoggingInterceptor" />
<interceptor-stack name="myStack">
<interceptor-ref name="myLogger" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="myStack" />
...
</package>
...
3) Test the interceptor with any URL that invokes a Struts2 action. Check the server console for output statements from the interceptor.
http://localhost:8080/WebAppName/AnyAction.action
No comments:
Post a Comment