Struts Short Notes 1
Struts Short Notes 1
x:-
Struts Flow:-
Struts 1.x Flow - in 10 Simple Steps
Hi All,
Here are the simple 10 steps for how Struts Framework will work - It is a general question in
many Interviews!
Initially let us assume /login.do is our action - the result will be successful login. Here I will
explain 15 steps how/what Struts framework will do ?
1) As end user triggerred / clicked on /login.do - > as usual it is a web application - first it will
look for Web.xml
So here - Web.xml loading is the first step!
2) In Web.xml it looks for *.do mapping and it finds the Struts plug-in i.e. ActionServelt and it
loads the same.
Example of Mapping:
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
.....
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
3) As part of loading ActionServlet calls the init() as every other servlet does.
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
So it loads the struts-config.xml - Same here you can configure multiple strtus config xml files
(Note: ActionServlet extends HttpServlet only)
6) It then calls the setters and reset() methods in the form bean or POJO or Java Bean class
(which extends ActionForm) corresponds to the mapped action. (Or else you can avoid this class
by writing DynaActionForm - i.e. you can create beans in config xml itself)
7) If the action tag in struts-config.xml contains validate "true"then the validate method will
call. So that you can check for normal validations like string length or mismatch of strings/
passwords etc. If any validation messages exist - add them to MessageCollection and iterate
them in your front end jsp page. If not it will redirect to the Action class - to perform actual
Business Logic.
8) Inside Action class - execute() method performs the business logic by calling internal
methods/DAO calls (you can use Hibernate whatever - as this is not related to Struts
concept) which you provide and based on these method calls it returns with
an ActionForward string key. (of course you have to set the result in session.setAttribute to get
these result in resulting jsp)
9) Now the returned string key will search for corresponding forward jsp (Inside <action> tag
using <forward> tag you can mention the forward names)
10) It looks for the appropriate view component and performs the getter on that action form
corresponding to this view component and loads the view page in the browser. (Iterate the
result from session.getAttribute which you have set while you returned from the DAO calls)!
Struts is an open source framework from Apache Software Foundation for developing well-
architected Webapplications. Based on the Model-View-Controller (MVC 2) design.
1. The Controller Servlet handles the user’s request. (This means the hyperlink in the JSP should
point to the controller servlet).
2. The Controller Servlet then instantiates appropriate JavaBeans based on the request
parameters (and optionally also based on session attributes).
3. The Controller Servlet then by itself or through a controller helper communicates with the
middle tier or directly to the database to fetch the required data.
4. The Controller sets the resultant JavaBeans (either same or a new one) in one of the
following contexts – request, session or application.
5. The controller then dispatches the request to the next view based on the request URL.
6. The View uses the resultant JavaBeans from Step 4 to display data.
Note that there is no presentation logic in the JSP. The sole function of the JSP in MVC 2
architecture is to display the data from the JavaBeans set in the request, session or application
scopes.
Model:
Model is responsible for providing the data from the database and saving the data into the data
store.
All the business logics are implemented in the Model.
Data entered by the user through View are checked in the model before saving into the
database.
Data access, Data validation and the data saving logic are part of Model.
View:
View represents the user view of the application and is responsible for taking the input from
the user.
Dispatching the request to the servletcontroller and then receiving response from the
controller to display the result to the user.
HTML, JSP files are the part of view component.
Controller:
Controller acts as a bridge between Model and View.
Controller is responsible for receiving the request from client.
Once request is received from client it executes the appropriate business logic from the Model
and then produce the output to the user using the View component.
ActionServlet class:
Action Servlet is a built in classes provided by struts F/W.
Action Servlet is a back bone of struts app’s
Actionservlet is a controller component that handle the all the client request
It is extended from org.apache.struts.action.actionServlet is called actionServlet.
In Struts, there is only one controller servlet for the entire web application. This controller
servlet is called ActionServlet and resides in the package org.apache.struts.action. And, struts
‘controller servlet’ which extends the javax.servlet.http.HttpServlet class.
The framework provides you with a controller servlet (ActionServlet) which is defined in the
Struts libraries
that are included in the IDE and it is configured as Servlet in the web.xml file.
The ActionServlet then instantiates a Handler. The Handler class name is obtained from an XML
file based on the URL path information. This XML file is referred to as Struts configuration
file and by default named as struts-config.xml.
The Handler is called Action in the Struts terminology. This class is created by extending the
Action class in org.apache.struts.action.Action package.
The Action class is abstract and defines a single method called execute(). You override this
method in your
own Actions and invoke the business logic in this method. The execute() method returns the
name of next view (JSP) to be shown to the user.
The controller servlet uses a struts-config.xml file to map incoming requests to
Struts Action objects and instantiate any ActionForm objects.
ActionForm class:
A Struts ActionForm is used to persist data between requests. (ActionForm is a normal
JavaBeans class.). It has several attributes corresponding to the HTTP request parameters and
getter, setter methods for those attributes.
You have to create your own ActionForm for every HTTP request handled through the Struts
framework by extending the org.apache.struts.action.ActionForm class.
Consider the following HTTP request for App1 web application –
http://localhost:8080/App1/create.do?firstName=John&lastName=Doe.
The ActionForm class for this HTTP request is shown below. The class LoginForm extends
theorg.apache.struts.action.ActionForm class and contains three attributes – name and email.
It also has getter and setter methods for these attributes.
package com.myapp.struts;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
public class LoginForm extends org.apache.struts.action.ActionForm {
private String name;
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String string) {
name = string;
}
public LoginForm() {
super();
}
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if (getName() == null || getName().length() < 1) {
errors.add(“name”, new ActionMessage(“error.name.required”));
// TODO: add ‘error.name.required’ key to your resources
}
return errors;
}
}
Action class:
Struts guys are developed some pre-defined action classes . all these action classes are
available in org.apache.struts.action package.
. all these action classes are available in struts-extra.jar file.
2. Dispatch action
Dispatch Action is an abstract classes extends actions. In this class doesn’t contain any abstract
methods
While developing any app’s if you want to implement multiple logic in a single action class then
we can implements all the logic in side the execute method
In case of dispatch action class we can write multiple method in a single action class where
each method follows signature of execute method like add(),update(),delete()
2. LookupDispatchAction:
<action-mappings>
<action path="/menu"
type="org.apache.struts.actions.IncludeAction"
parameter="/menu.jsp/>
</action-mappings>
page: A module-relative URI (beginning with /) to which control should be forwarded after switching.
prefix: The module prefix (beginning with /) of the application module to which control should be
switched. Use a zero-length string for the default module. The appropriate ApplicationConfig object
will be stored as a request attribute, so any subsequent logic will assume the new application module.
struts provides a small, but effective exception-handling framework for the applications. There are two
approaches available for the exception handling in struts.
1. Declarative:- In this approach the exceptions are defined in the struts-config file and in case of the
exception occurs the control is automatically passed to the appropriate error page. The tag is used to
define the exception in the struts-config.xml file. The following are the attributes of the tag.
1. Key:- The key defines the key present in MessageResources.properties file to describe the exception
occurred.
2. Type:- The class of the exception occurred.
3. Path:- The page where the control is to be followed in case exception occurred.
4. Handler:- The exception handler which will be called before passing the control to the file specified in
path attribute
There are following two sections in struts-config.xml where you can define the exceptions.
* With Any Action mapping:- In this approach the action class is identified which may throw the exception
like password failure, resource access etc. For example:-
Code
1. <action path="/exception"
2. type="com.visualbuilder.ExampleAction"
3. parameter="method"
4. input="/index.jsp" >
6. </action>
7.
* Defining the Exceptions Globally for the struts-config.xml :- If the application control is to pass on a
single page for all similar type of exception then the exception can be defined globally. So if in any
circumstance the exception occurs the control is passed globally to the exception and control is passed to
the error page. For Example:-
Code
1. <global-exceptions>
3. </global-exceptions>
4.
2. Programmatic: - In this approach the exceptions are caught using normal java language try/catch
block and instead of showing the exception some meaningful messages are displayed. In this approach
the flow of control is also maintained by the programs. The main drawback of the approach is the
developer has to write the code for the flow of the application.
1. Java Servlets
2. JSP (Java Server Pages)
3. Custom Tags
4. Message Resources
Q2. What’s the role of a handler in MVC based applications?
Ans:. It’s the job of handlers to transfer the requests to appropriate models as they are bound
to the model layer of MVC architecture. Handlers use mapping information from configuration
files for request transfer.
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.
Q4. Which file is used by controller to get mapping information for request routing?
Ans: Controller uses a configuration file “struts-config.xml file to get all mapping information to
decide which action to use for routing of user’s request.
Ans: In Struts, Action Class acts as a controller and performs following key tasks:
1 import javax.servlet.http.HttpServletRequest;
2 import org.apache.struts.action.*;
3 public class testForm extends ActionForm {
4 private String Id=null;
5 private String State=null;
6 public void setId(String id){
7 this.Id=id;
8 }
9 public String getId(){
10 return this.Id;
11 }
12 public void setState(String state){
13 this.State=state;
14 }
15 public String getState(){
16 return this.State;
17 }
Q7. What are the two types of validations supported by Validator FrameWork?
Ans: Validator Framework is used for form data validation. This framework provides two types
of validations:
Ans: In order to use Struts framework, we only need to add Struts.Jar file in our development
environment. Once jar file is available in the CLASSPATH, we can use the framework and
develop Strut based applications.
Ans: In order to enable client side validation in Struts, first we need to enable validator plug-in
in struts-config.xml file. This is done by adding following configuration entries in this file:
Then Validation rules are defined in validation.xml file. If a form contains email field and we
want to enable client side validation for this field, following code is added in validation.xml file:
1 <form name="testForm">
2 <field property="email"
3 depends="required">
4 <arg key="testForm.email"/>
5 </field>
6 </form>
Q10. How action-mapping tag is used for request forwarding in Struts configuration file?
Ans: 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:
This forwarding will take place when user will click on following hyperlink on the jsp page:
Ans: In Struts, action class provides two important methods which can be used to avoid
duplicate form submissions.
saveToken() method of action class generates a unique token and saves it in the user’s session.
isTokenValid() method is used then used to check uniqueness of tokens.
Q12. In Struts, how can we access Java beans and their properties?
Ans: Bean Tag Library is a Struts library which can be used for accessing Java beans.
Q13. Which configuration file is used for storing JSP configuration information in Struts?
Ans: Execute method of action class is responsible for execution of business logic. If any
processing is required on the user’s request, it’s performed in this method. This method returns
actionForward object which routes the application to appropriate page.
In the following example, execute method will return an object of actionForward defined in
struts-config.xml with the name “exampleAction”:
1 import javax.servlet.http.HttpServletRequest;
2 import javax.servlet.http.HttpServletResponse;
3
4 import org.apache.struts.action.Action;
5 import org.apache.struts.action.ActionForm;
6 import org.apache.struts.action.ActionForward;
7 import org.apache.struts.action.ActionMapping;
8
9 public class actionExample extends Action
10 {
11 public ActionForward execute(
12 ActionMapping mapping,
13 ActionForm form,
14 HttpServletRequest request,
15 HttpServletResponse response) throws Exception{
16 return mapping.findForward("exampleAction");
17 }
18 }
Q15. What’s the difference between validation.xml and validator-rules.xml files in Struts
Validation framework?
Ans: In Validation.xml, we define validation rules for any specific Java bean while in validator-
rules.xml file, standard and generic validation rules are defined.
Q16. How can we display all validation errors to user on JSP page?
Ans: To display all validation errors based on the validation rules defined in validation.xml file,
we use <html:errors /> tag in our JSP file.
Ans: When logic for exception handling is defined in struts-config.xml or within the action tag,
it’s known as declarative exception handling in Struts.
1 <global-exceptions>
2
3 <exception key="test.key"
4
5 Type="java.lang.NullPointerException"
6
7 Path="/WEB-INF/errors/error_page.jsp"
8
9 </global-exceptions>
Ans: DynaActionForm is a special type of actionForm class (sub-class of ActionForm Class) that’s
used for dynamically creating form beans. It uses configuration files for form bean creation.
Ans: To create reusable components with Tiles framework, we need to add following plugin
definition code in struts-config.xml file:
Q20. What’s the difference between Jakarta Struts and Apache Struts? Which one is better to
use?
Ans: Both are same and there is no difference between them.
Ans: Struts.xml file is one the key configuration files of Struts framework which is used to define
mapping between URL and action. When a user’s request is received by the controller,
controller uses mapping information from this file to select appropriate action class.
Ans: Tag libraries are defined in the configuration file (web.xml) inside <taglib> tag as follows:
1 <taglib>
2
3 <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
4
5 <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
6
7 </taglib>
Ans: Use of logic tags in Struts helps in writing a clean and efficient code at presentation layer
without use of scriptlets.
Ans: 1. Request Scope: Formbean values are available in the current request only
2. Session Scope: Formbean values are available for all requests in the current session.
Ans: To group multiple related actions in one group, we can use DispatcherAction class.
Ans: 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.
Q28. What steps are required to for an application migration from Struts1 to Struts2?
Ans: For validation of populated properties, validate() method of ActionForm class is used
before handling the control of formbean to Action class.
Ans: reset method of actionForm class is used to clear the values of a form before initiation of a
new request.
Ans: 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.
Ans: resourcebundle.properties file is used to define specific error messages in key value pairs
for any possible errors that may occur in the code.
This approach helps to keep the code clean as developer doesn’t need to embed all error
messages inside code.
Q33. Can I have html form property without associated getter and setter formbean methods?
Ans: For each html form property, getter and setter methods in the formbean must be defined
otherwise application results in an error.
Ans: Struts framework works on the concept of centralized control approach and the whole
application is controlled by a single servlet controller. Hence, we require only one servlet
controller in a servlet application.
Q35. For a single Struts application, can we have multiple struts-config.xml files?
Ans: We can have any number of Struts-config.xml files for a single application.
Ans: 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.
Ans: IncludeAction is action class provided by Struts which is useful when an integration is
required between Struts and Servlet based application.
Ans: Yes Struts are thread safe. In Struts, a new servlet object is not required to handle each
request; rather a new thread of action class object is used for each new request.
Q39. What configuration changes are required to use resource files in Struts?
Ans: Resource files (.properties files) can be used in Struts by adding following configuration
entry in struts-config.xml file:
<message-resources parameter=”com.login.struts.ApplicationResources”/>
Ans: Struts provide a separate tag library (Nested Tag Library) for this purpose. Using this
library, we can nest the beans in any Struts based application.
Action Class
ActionForm Class
ActionMapping Class
ActionForward Class
ActionServlet Class
Q42. Can we handle exceptions in Struts programmatically?
Ans: Yes we can handle exceptions in Struts programmatically by using try, catch blocks in the
code.
1 try {
2
3 // Struts code
4
5 }
6
7 Catch (Exception e) {
8
9 // exception handling code
10
11 }
Ans: Although Struts framework is based on J2EE technologies like JSP, Java Beans, Servlets etc
but it’s not a part of J2EE standards.
Ans: Action mappings are configured in the configuration file struts-config.xml under the tag
<action-mapping> as follows:
1 <pre><action-mappings>
2 <action path="/login"
3 type="login.loginAction"
4 name="loginForm"
5 input="/login.jsp"
6 scope="request"
7 validate="true">
8 <forward name="success" path="/index.jsp"/>
9 <forward name="failure" path="/login_error.jsp"/>
10 </action>
11 </action-mappings>
Ans: Struts should be used when any or some of the following conditions are true:
Ans: In Struts framework, actionServlet acts as a controller and all the requests made by users
are controlled by this controller. ActionServlet is based on singleton design patter as only one
object needs to be created for this controller class. Multiple threads are created later for each
user request.
Q47. What are the steps required for setting up validator framework in Struts?
Ans: Following Steps are required to setup validator framework in Struts: – Wrong Spelling
1. In WEB-INF directory place valdator-rules.xml and validation.xml files.
2. Enable validation plugin in struts-config.xml files by adding following:
1 <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
2 <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,
3 /WEB-INF/validation.xml"/>
4 </plug-in>
Ans: In Struts, we can use any of the following technologies in view layer:
JSP
HTML
XML/XSLT
WML Files
Velocity Templates
Servlets
Q49. What are the conditions for actionForm to work correctly?
Ans: Struts provide HTML Tags library which can be used for adding form elements like text
fields, text boxes, radio buttons etc.