Interceptors in Struts2
What are Interceptors?
Interceptors are used for performing operations like Validation, file upload, exception handling etc.
Advantages of Interceptors:
Separation of Concerns, If we need to remove any of the concerns like validation or exception handling etc.. We can remove them from struts.xml without disturbing the application.
Default Interceptors:
Struts 2 has some in-built default interceptors, also we can build our own custom interceptors. In this post, we are going to explore default interceptors.
conversionError | Error message when converting string to parameter value |
Lets see an example,
Lets check the “timer” interceptor to check the time taken for executing the action.
Structure:
first.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Interceptor</title> </head> <body> <s:form action="check"> <s:submit value="Intercept"/> </s:form> </body> </html>
display.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Display</title> </head> <body> Intercepted Successfully! <s:property value="name"/> </body> </html>
Sdao.java
public class Sdao extends ActionSupport { @Override public String execute() { return "success"; } }
struts.xml
<struts> <include file="example.xml"/> <!-- Configuration for the default package. --> <package name="default" extends="struts-default"> <action name="check" class="Dao.Sdao" method="execute"> <interceptor-ref name="timer"/> <result name="success">/display.jsp</result> </action> </package> </struts>
Output:
In your log file you can see the output of timer interceptor,
[…] 2 provide a set of default interceptors (default interceptors), we can also create and implement our own interceptors. Creating and implementing own interceptors […]
[…] is one of the default-Interceptor in Struts (you can view default-interceptors here). The execAndWait interceptor shows an intermediate webpage when result page is […]
[…] Uploading files in Struts Struts has default interceptor (in-build interceptor) for uploading files, however not that these files will get stored in temporary directory they should be processed and stored in permanent location. (Refer: Default Interceptors in Struts) […]