Google News
logo
Java Struts Interview Questions
Struts is a free, MVC-based, open-source framework that helps developers create modern Java applications. This framework prefers convention over configuration and is extensible through a plugin architecture.
 
Struts was initially built by Craig McClanahan. The first stable version was released in June 2001. Struts 2.0 was released in 2014.
Apache Struts2 is an open source framework to build web applications in Java. Struts2 is based on OpenSymphony WebWork framework. It’s highly improved from Struts1 and that makes it more flexible, easy to use and extend. The core components of Struts2 are Action, Interceptors and Result pages.
 
Struts2 provides many ways to create Action classes and configure them via struts.xml or through annotations. We can create our own interceptors for common tasks. Struts2 comes with a lot of tags and uses OGNL expression language. We can create our own type converters to render result pages. Result pages can be JSPs and FreeMarker templates.
* JSP Programs or View Layer Resources
* FormBean Class Java Class or Controller Layer Resources
* Action Servlet Built-in Controller Servlet or Controller Layer Resources
* Action Class Java Class or Controller Layer Resources
* web.xml Deployment Descriptor file of the web application
* Struts Configuration File XML File or Controller Layer Resources
Structs1 : 
* Form beans define properties, setters and getters
* Execute() method exposes servlet API for testing
* Multiple tag libraries
* RequestProcessor class present
* Struts1 APIs are tightly coupled with Servlet API and Request and Response objects are passed to action classes execute() method.
* Struts1 action classes are hard to test because of Servlet API coupling.
* Struts1 requires us to create ActionForm classes to hold request params and we need to configure it in the struts configuration file.
* Struts1 uses JSTL Tags and hence are limited.
* Struts1 supports validation through manual validate() method

Structs2 : 
* Getters and Setters are defined in action classes
* Dependency Injection simplifies the testing process
* The single library includes all tags
* Interceptors present
* Struts2 API is loosely coupled with Servlet API and automatically maps the form bean data to action class java bean properties that we mostly use. If however we need reference to Servlet API classes, there are *Aware interfaces for that.
* Struts2 Action classes are like normal java classes and we can test them easily by instantiating them and setting their properties.
* Struts2 request params mapping is done on the fly and all we need is to have java bean properties in action classes or implement ModelDriven interface to provide the java bean class name to be used for mapping.
* Struts2 uses OGNL and provide different kinds of UI, Control and Data Tags. It’s more versatile and easy to use.
* Struts2 support both manual validation as well as Validation framework integration.
The prominent features of Struts2 are as follows :
 
* In Struts2, the Action class is POJO. We don’t need to inherit any class or implement any interface.
* Struts2 has JSP, Free marker, and Valocity for the view component.
* In Struts2, Front Controller is StrutsPrepareAndExecuteFilter.
* In Struts2, the configuration file name must be struts.xml and should be placed inside the classes directory.
* Struts2 uses the concept of Interceptors while processing the request.
Struts framework is comprised of following components :
 
* Java Servlets
* JSP (Java Server Pages)
* Custom Tags
* Message Resources
Struts based applications use MVC design pattern. The flow of requests is as follows :
 
* User interacts with View by clicking any link or by submitting any form.
* Upon user’s interaction, the request is passed towards the controller.
* Controller is responsible for passing the request to appropriate action.
* Action is responsible for calling a function in Model which has all business logic implemented.
* Response from the model layer is received back by the action which then passes it towards the view where user is able to see the response.
In Struts, Action Class acts as a controller and performs following key tasks :
 
* After receiving user request, it processes the user’s request.
* Uses appropriate model and pulls data from model (if required).
* Selects proper view to show the response to the user.
Enlisted below are the most important classes of the Struts Application.
 
Action Servlet : It is the controller class and handles all the incoming requests.
Action Class : With Action class all the business logic also so-called a Model is developed.
Action Form : Action Form is a java bean that associates one or more Action Mappings. It maintains the session state for a web application.
Action Mapping : With Action Mapping, we can do the mapping between Object and Action.
Action Forward : It is used to forward the result from the Controller to the destination.
When we need to join a current application with struts, we have to utilize the Forward Action. Forward Action is also utilized at whatever point one needs to transfer the entire control starting with one place then onto the next, say, JSP to a nearby server. The Forward Action is also utilized when one needs to acquire the advantages of the usefulness of struts after the integration with Struts. For this situation, Servlets are never written again. Another utilization of forwarding Action is when a request is sent to different assets.
Interceptors are the backbone of Struts2 Framework. Struts2 interceptors are responsible for most of the processing done by the framework, such as passing request params to action classes, making Servlet API request, response, session available to Action classes, validation, i18n support, etc.
 
ActionInvocation is responsible to incapsulate Action classes and interceptors and to fire them in order. The most important method for use in ActionInvocation is invoke() method that keeps track of the interceptor chain and invokes the next interceptor or action. This is one of the best example of Chain of Responsibility pattern in Java EE frameworks.
Struts2 interceptors are based on intercepting filters design pattern. The invocation of interceptors in interceptor stack closely resembles Chain of Responsibility design pattern.
Struts2 Action classes are thread safe because an object is instantiated for every request to handle it.
 
Struts2 interceptors are singleton classes and a new thread is created to handle the request, so it’s not thread safe and we need to implement them carefully to avoid any issues with shared data.
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter is the Front Controller class in Struts2 and every request processing starts from this class. Earlier versions of Struts2 uses org.apache.struts2.dispatcher.FilterDispatcher as Front Controller class.
Technically, there is no difference between them Apache Struts and Jakarta Struts. They are both similar. Craig McClanahan created Struts and donated it to Apache Foundation. Later, it evolved as a Jakarta project and gained popularity in the J2EE community.
To configure the Struts2 action mapping we have to add an action node inside the configuration file struts.xml.
 
Here is an example for this:
<action name="*welcome" class="example.action.mapping.LinkAction" method="execute">

     <result name="success">/welcome.jsp</result>

     <result name="error">/error.jsp</result>

</action>
* The DispatchAction enable the programmer to combine together related function or class.
* Using Dispatch Action programmer can combine the user related action into a single UserAction. like add user, delete user and update user.
* DispatchAction execute the action based on the parameter value it receives from the user.
We can use the Dispatch Action we executing following steps :
 
* Create a class that extends DispatchAction.
* In a new class, add a method : method has the same signature as the execute() method of an Action class.
* Do not override execute() method.
* Add an entry to struts-config.xml
Validate () method is used to validate the properties after they have been populated and it is called before the Form Bean is passed to the action. It returns a collection of action errors.
 
Syntax : Public ActionErrors Validate (ActionMapping mapping, HttpServletRequest request)
 
Reset () method is used to reset all the ActionForm’s data before the new values are being set. It is called by the struts framework with each request that uses a defined action form.
 
Syntax : public void reset ((ActionMapping mapping, HttpServletRequest request)
Object Graph Navigation Language (OGNL) is a strong expression language. It helps to simplify the accessibility of data stored in the ActionContext. OGNL supports interacting with collections i.e. Map, List, and Set.
 
The struts framework helps to set the ValueStack as the root object of OGNL. The action object is pushed into the ValueStack and we can directly access the action property.
Struts provides many tag libraries to ease software development.
 
They are :
 
Bean Tag Library : Used for accessing Java Beans and its properties.
Nested Tag Library : Provides the ability to use nested beans in the application.
Logic Tag Library : Used for giving the required output, iteration capability and flow management.
HTML Tag Library : Helps to get the required HTML output.
Tiles Tag library : Used in applications that have tiles.
There are 5 types of Struts Actions.
 
They are as follows :
 
Forward Action : With this class, we can control the Struts controller and its functionality, without having to rewrite the existing Servlets.
Include Action : Using IncludeAction class to include another resource in the response to the request being processed.
Switch Action : Used to switch one resource in one module to another resource in another module.
Dispatch Action : Used to combine the related actions into a single class.
LookUpAction : Used to drive the action with a key if the action name is not working.
The various types of tags in Struts2 are as follows :
 
Control Tag (If Else tag, Iterator Tag, Merge Tag, Append Tag, Generator Tag, etc.)
Data Tag (Action tag, Include Tag, Bean Tag, Date Tag, Param Tag, Property Tag, Push Tag, Set Tag, Text Tag, etc.)
Form Tag (All the simple UI Tags.)
Ajax Tag
In Struts configuration file (struts-config.xml), forwarding options are defined under action-mapping tag.
 
In the following example, when a user will click on the hyperlink test.do, request will be forwarded to /pages/testing.jsp using following configurations from struts-config.xml file :
 
<action  path="/test" forward="/pages/testing.jsp">
 
This forwarding will take place when user will click on following hyperlink on the jsp page :
 
<html:link</strong> page="/test.do</strong>">Controller Example</html:link>
To create reusable components with Tiles framework, we need to add following plugin definition code in struts-config.xml file :
<plug-in className="org.apache.struts.tiles.TilesPlugin" >

<set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml" />

<set-property property="moduleAware" value="true" />

</plug-in>
com.opensymphony.xwork2.interceptor.ParametersInterceptor interceptor is responsible for mapping request parameters to the Action class java bean properties. This interceptor is configured in struts-default package with name “params”. This interceptor is part of basicStack and defaultStack interceptors stack.
Struts2 action classes don’t provide direct access to Servlet API components such as Request, Response, and Session. However, sometimes we need these access in action classes such as checking HTTP method or setting cookies in response.
 
That’s why Struts2 API provides a bunch of *Aware interfaces that we can implement to access these objects. Struts2 API uses dependency injection to inject Servlet API components in action classes. Some of the important Aware interfaces are SessionAware, ApplicationAware, ServletRequestAware, and ServletResponseAware.
Interceptor interface defines three methods – init(), destroy() and intercept(). init and destroy are the life cycle methods of an interceptor. Interceptors are Singleton classes and Struts2 initialize a new thread to handle each request. init() method is called when interceptor instance is created and we can initialize any resources in this method. destroy() method is called when application is shutting down and we can release any resources in this method.
The default URI suffix for Struts2 action is .action, in Struts1 default suffix was .do. We can change this suffix by defining struts.action.extension constant value in our Struts2 configuration file as :
 
<constant name="struts.action.extension" value="action,do"></constant>
By default Struts2 looks for result pages in {WEBAPP-ROOT}/{Namespace}/ directory but sometimes we want to keep result pages in another location, we can provide struts.convention.result.path constant value in Struts2 configuration file to change the result pages location.
 
Another way is to use @ResultPath annotation in action classes to provide the result pages location.
Struts2 provides a very robust framework for exception handling. We can specify global results in packages and then map specific exceptions to these result pages. The exception mapping can be done at the global package level as well as the action level.
 
It’s a good idea to have exception result pages to provide some information to the user when some unexpected exception occurs that is not processed by the application. The sample configuration in the struts.xml file looks like below.

<package name="user" namespace="/" extends="struts-default">
 
<global-results>
    <result name="exception">/exception.jsp</result>
    <result name="runtime_exception">/runtime_exception.jsp</result>
    <result name="error">/error.jsp</result>
</global-results>
 
<global-exception-mappings>
    <exception-mapping exception="java.lang.Exception" result="exception"></exception-mapping>
    <exception-mapping exception="java.lang.Error" result="error"></exception-mapping>
    <exception-mapping exception="java.lang.RuntimeException" result="runtime_exception"></exception-mapping>
</global-exception-mappings>
 
    <action name="myaction" class="com.journaldev.struts2.exception.MyAction">
    </action>
    <action name="myspecialaction" class="com.journaldev.struts2.exception.MySpecialAction">
    <exception-mapping exception="java.io.IOException" result="login"></exception-mapping>
    <result name="login">/error.jsp</result>
    </action>
</package>​
Struts.xml file is one the major configuration records of Struts system which is utilized to characterize mapping between URL and action. At the point when the controller receives a client’s demand, the controller utilizes mapping data from this file to choose appropriate action class.
Struts is based on MVC and hence there is a good separation of different layers in Struts which makes Struts applications development and customization easy. Use of different configuration files makes Struts applications easily configurable. Also, Struts is open source and hence, cost effective.
Although Struts have large number of advantages associated, it also requires bigger learning curve and also reduces transparency in the development process.
 
Struts also lack proper documentation and for many of its components, users are unable to get proper online resources for help.
Struts support all types of models including Java beans, EJB, CORBA. However, Struts doesn’t have any in-built support for any specific model and it’s the developer’s choice to opt for any model.
Following are the core classes provided by Struts Framework :
 
* Action Class
* ActionForm Class
* ActionMapping Class
* ActionForward Class
* ActionServlet Class
In Struts, we can use any of the following technologies in view layer :
 
* JSP
* HTML
* XML/XSLT
* WML Files
* Velocity Templates
* Servlets