Struts 2 creating own interceptor
In this tutorial, it shows how to create an own interceptor in Struts 2.
Summary steps :
- Create a class implements com.opensymphony.xwork2.interceptor.Interceptor.
- Implement the intercept(ActionInvocation invocation) method.
- Configure the interceptor in the struts.xml.
- Link it to action.
Struts 2 comes with many ready interceptors, make sure you check the list of the available Struts 2 interceptors before you create your own interceptor.
A complete example to create an own interceptor :
1. Action
A simple action to forward the user request and print a message.
HelloAction.java
package com.mkyong.common.action; import com.opensymphony.xwork2.ActionSupport; public class HelloAction extends ActionSupport{ public String execute() throws Exception { System.out.println("HelloAction execute() is called"); return SUCCESS; } }
2. Interceptor
A full interceptor example.
PrintMsgInterceptor.java
package com.mkyong.common.interceptor; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.Interceptor; public class PrintMsgInterceptor implements Interceptor{ //called during interceptor destruction public void destroy() { System.out.println("CustomInterceptor destroy() is called..."); } //called during interceptor initialization public void init() { System.out.println("CustomInterceptor init() is called..."); } //put interceptor code here public String intercept(ActionInvocation invocation) throws Exception { System.out.println("CustomInterceptor, before invocation.invoke()..."); String result = invocation.invoke(); System.out.println("CustomInterceptor, after invocation.invoke()..."); return result; } }
Explanation
The interceptor class must implements the com.opensymphony.xwork2.interceptor.Interceptor interface. During interceptor initialization, init() is called; interceptor destruction, destroy() is called. In last, put all interceptor code that does the work inside the intercept(ActionInvocation invocation) method.
In the interceptor intercept() method, you must called the invocation.invoke() and return it’s result. This is the method responsible for calling the next interceptor or the action. The action will failed to continue without calling the invocation.invoke() method.
It’s not recommend to put any code inside the destroy(), because this method is not reliable. When your application server is force shutdown or be killed by command, the destroy() will not be called.
3. struts.xml
Configure the interceptor in the struts.xml file.
<?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" namespace="/" extends="struts-default"> <interceptors> <interceptor name="printMsgInterceptor" class="com.mkyong.common.interceptor.PrintMsgInterceptor"></interceptor> <interceptor-stack name="newStack"> <interceptor-ref name="printMsgInterceptor"/> <interceptor-ref name="defaultStack" /> </interceptor-stack> </interceptors> <action name="helloAction" class="com.mkyong.common.action.HelloAction" > <interceptor-ref name="newStack"/> <result name="success">pages/hello.jsp</result> </action> </package> </struts>
4. Demo
During the server initialization, the interceptor init() method is called.
INFO: Overriding property struts.i18n.reload - old value: false new value: true 15 Julai 2010 11:37:42 AM com.opensymphony.xwork2.util.logging.commons.CommonsLogger info INFO: Overriding property struts.configuration.xml.reload - old value: false new value: true CustomInterceptor init() is called... 15 Julai 2010 11:37:42 AM org.apache.coyote.http11.Http11Protocol start INFO: Starting Coyote HTTP/1.1 on http-8080 15 Julai 2010 11:37:42 AM org.apache.jk.common.ChannelSocket init INFO: JK: ajp13 listening on /0.0.0.0:8009 15 Julai 2010 11:37:42 AM org.apache.jk.server.JkMain start INFO: Jk running ID=0 time=0/20 config=null 15 Julai 2010 11:37:42 AM org.apache.catalina.startup.Catalina start INFO: Server startup in 994 ms
While you access the action via URL : http://localhost:8080/Struts2Example/helloAction.action
INFO: Overriding property struts.i18n.reload - old value: false new value: true 15 Julai 2010 11:37:42 AM com.opensymphony.xwork2.util.logging.commons.CommonsLogger info INFO: Overriding property struts.configuration.xml.reload - old value: false new value: true CustomInterceptor init() is called... 15 Julai 2010 11:37:42 AM org.apache.coyote.http11.Http11Protocol start INFO: Starting Coyote HTTP/1.1 on http-8080 15 Julai 2010 11:37:42 AM org.apache.jk.common.ChannelSocket init INFO: JK: ajp13 listening on /0.0.0.0:8009 15 Julai 2010 11:37:42 AM org.apache.jk.server.JkMain start INFO: Jk running ID=0 time=0/20 config=null 15 Julai 2010 11:37:42 AM org.apache.catalina.startup.Catalina start INFO: Server startup in 994 ms CustomInterceptor, before invocation.invoke()... HelloAction execute() is called CustomInterceptor, after invocation.invoke()...

I do not understand why the message “HelloAction execute() is called” occurs before message
“CustomInterceptor, after invocation.invoke()…”
Could you explain about my concern ?
As you know, interceptors is used to pre and post request processing.
In pre processing “CustomInterceptor, before invocation.invoke()…” will print. While calling of String result = invocation.invoke(); the execution will go to action class and “HelloAction execute() is called” will be printed. now “CustomInterceptor, after invocation.invoke()…” is post processing of request which execute after action class.
I do not understand why the message “HelloAction execute() is called” occurs before message
“CustomInterceptor, after invocation.invoke()…”
Could you explain for my concern ?
Please clarify my doubt? iam new to struts2
i have an custom interceptor for checking session valid or not. i am returning “login” if session is invalid. now my aim is to display login page if the if interceptor returns “login” . but i dont know how to handle returned string “loing” here is my code.
my action class is as follows:
Excellent post.
I make an interceptor to manage my Hibernate transactions.
In this applications, I work with annotations. It’s my first time. And I want to link my action with my created interceptor. I know that I have the annotations: InterceptorRef or InterceptorRefs to link my action. But, is there some annotation to declare my interceptor without use the struts.xml file?
Thanks.
exception while working with interceptor:
type Exception report
message
descriptionThe server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: The Struts dispatcher cannot be found. This is usually caused by using Struts tags without the associated filter. Struts tags are only usable when the request has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag. – [unknown location]
root cause
The Struts dispatcher cannot be found. This is usually caused by using Struts tags without the associated filter. Struts tags are only usable when the request has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag. – [unknown location]
note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 3.1.1 logs.
coding in mapping file
—session.xml—
?
index.jsp
—srtuts.xml—
oh, i get it !
Maybe the jar is broken
2012-6-21 9:05:40 org.apache.catalina.loader.WebappClassLoader modified
??: Additional JARs have been added : ‘struts2-dojo-plugin-2.1.8.jar’
There is something wrong when i run the program on Tomcat 6, something wrong happened,that is “CustomInterceptor init() is called…” is printed out every 2 seconds, when I don’t even make any request to the application. Why?
==============================
2012-6-21 9:05:17 org.apache.tomcat.util.digester.SetPropertiesRule begin
??: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property ‘source’ to ‘org.eclipse.jst.j2ee.server:Struts2ExampleInterceptor’ did not find a matching property.
2012-6-21 9:05:17 org.apache.catalina.core.AprLifecycleListener init
??: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Java\jdk1.5.0_06\bin;.;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Windows Resource Kits\Tools\;D:\oracle\ora92\bin;D:\app\liguocai\product\11.1.0\db_1\bin;D:\oracle\ora92\bin;C:\Java\jdk1.5.0_06\bin;C:\Program Files\Oracle\jre\1.3.1\bin;C:\Program Files\Oracle\jre\1.1.8\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\NTRU Cryptosystems\NTRU TCG Software Stack\bin\;E:\DevEnviroment\TortoiseSVN\bin;E:\DevEnviroment\apache-ant-1.8.2\bin;C:\WINDOWS\system32\WindowsPowerShell\v1.0;C:\Program Files\Android\android-sdk\tools;E:\PROGRA~1\IBM\SQLLIB\BIN;E:\PROGRA~1\IBM\SQLLIB\FUNCTION;E:\PROGRA~1\IBM\SQLLIB\SAMPLES\REPL;F:\Program Files\Microsoft Visual Studio\Common\Tools\WinNT;F:\Program Files\Microsoft Visual Studio\Common\MSDev98\Bin;F:\Program Files\Microsoft Visual Studio\Common\Tools;F:\Program Files\Microsoft Visual Studio\VC98\bin;C:\Program Files\StormII\Codec;C:\Program Files\StormII;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;F:\python27;F:\python27\Scripts;
2012-6-21 9:05:17 org.apache.coyote.http11.Http11Protocol init
??: Initializing Coyote HTTP/1.1 on http-9080
2012-6-21 9:05:17 org.apache.catalina.startup.Catalina load
??: Initialization processed in 669 ms
2012-6-21 9:05:17 org.apache.catalina.core.StandardService start
??: Starting service Catalina
2012-6-21 9:05:17 org.apache.catalina.core.StandardEngine start
??: Starting Servlet Engine: Apache Tomcat/6.0.20
2012-6-21 9:05:17 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Parsing configuration file [struts-default.xml]
2012-6-21 9:05:18 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Unable to locate configuration files of the name struts-plugin.xml, skipping
2012-6-21 9:05:18 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Parsing configuration file [struts-plugin.xml]
2012-6-21 9:05:18 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Parsing configuration file [struts.xml]
2012-6-21 9:05:18 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Overriding property struts.i18n.reload – old value: false new value: true
2012-6-21 9:05:18 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Overriding property struts.configuration.xml.reload – old value: false new value: true
CustomInterceptor init() is called…
2012-6-21 9:05:19 org.apache.coyote.http11.Http11Protocol start
??: Starting Coyote HTTP/1.1 on http-9080
2012-6-21 9:05:19 org.apache.jk.common.ChannelSocket init
??: JK: ajp13 listening on /0.0.0.0:9016
2012-6-21 9:05:19 org.apache.jk.server.JkMain start
??: Jk running ID=0 time=0/31 config=null
2012-6-21 9:05:19 org.apache.catalina.startup.Catalina start
??: Server startup in 1903 ms
2012-6-21 9:05:29 org.apache.catalina.loader.WebappClassLoader modified
??: Additional JARs have been added : ‘struts2-dojo-plugin-2.1.8.jar’
2012-6-21 9:05:29 org.apache.catalina.core.StandardContext reload
??: Reloading this Context has started
CustomInterceptor destroy() is called…
2012-6-21 9:05:29 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Parsing configuration file [struts-default.xml]
2012-6-21 9:05:30 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Unable to locate configuration files of the name struts-plugin.xml, skipping
2012-6-21 9:05:30 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Parsing configuration file [struts-plugin.xml]
2012-6-21 9:05:30 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Parsing configuration file [struts.xml]
2012-6-21 9:05:30 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Overriding property struts.i18n.reload – old value: false new value: true
2012-6-21 9:05:30 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Overriding property struts.configuration.xml.reload – old value: false new value: true
CustomInterceptor init() is called…
2012-6-21 9:05:40 org.apache.catalina.loader.WebappClassLoader modified
??: Additional JARs have been added : ‘struts2-dojo-plugin-2.1.8.jar’
2012-6-21 9:05:40 org.apache.catalina.core.StandardContext reload
??: Reloading this Context has started
CustomInterceptor destroy() is called…
2012-6-21 9:05:41 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Parsing configuration file [struts-default.xml]
2012-6-21 9:05:41 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Unable to locate configuration files of the name struts-plugin.xml, skipping
2012-6-21 9:05:41 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Parsing configuration file [struts-plugin.xml]
2012-6-21 9:05:41 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Parsing configuration file [struts.xml]
2012-6-21 9:05:41 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Overriding property struts.i18n.reload – old value: false new value: true
2012-6-21 9:05:41 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Overriding property struts.configuration.xml.reload – old value: false new value: true
CustomInterceptor init() is called…
2012-6-21 9:05:51 org.apache.catalina.loader.WebappClassLoader modified
??: Additional JARs have been added : ‘struts2-dojo-plugin-2.1.8.jar’
2012-6-21 9:05:51 org.apache.catalina.core.StandardContext reload
??: Reloading this Context has started
CustomInterceptor destroy() is called…
2012-6-21 9:05:52 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Parsing configuration file [struts-default.xml]
2012-6-21 9:05:52 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Unable to locate configuration files of the name struts-plugin.xml, skipping
2012-6-21 9:05:52 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Parsing configuration file [struts-plugin.xml]
2012-6-21 9:05:52 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Parsing configuration file [struts.xml]
2012-6-21 9:05:52 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Overriding property struts.i18n.reload – old value: false new value: true
2012-6-21 9:05:52 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
??: Overriding property struts.configuration.xml.reload – old value: false new value: true
CustomInterceptor init() is called…