Professional Documents
Culture Documents
* Struts is open source Web Application Framework for developing Java EE web application Developed by Apache in
2000.
* Struts 1 Framework was implemented on MVC 2 architecture and Front Controller Design Pattern.
* Struts mainly deals with Presentation Layer and Controller Layer. Struts does not specify or force any rules related
to model layer.
We can use any thing in Model Layer as per our requirement.
* Struts can interact with standard data access technologies, like JDBC and EJB, as well as most any third-party
packages, like Hibernate, iBATIS, or Object Relational Bridge.
* Struts has 3 Components on Controller Layer ActionServlet, RequestProcessor, Actions.
* For the View, Struts works well with JSP, including JSTL and EL, Struts Tag Library, Message Bundles, Form
Beans as well as Velocity Templates, XSLT, and other presentation systems.
* Struts provide various Tag Libraries for different purpose.
* It was originally created by Craig McClanahan and donated to the Apache Foundation in May, 2000.
Advantage of Struts :
Thread Safe
Difference between Struts and JSF :
* Struts is a Framework but JSF is a Technology.
* JSF bean class is not extending any built-in class like Struts Action and Bean class methods are not taking any
Parameters like Struts execute() method.
* The faces-config.xml is much easier to use than is the struts-config.xml file. In general, JSF is simpler.
* An event and listener model that defines how to handle events generated by activating a component, such as what to
do when a user clicks a button. Struts is not.
* The Struts validation framework includes a larger set of standard validators, which automatically generate both
server-side and client-side validation code based on a set of rules in a configuration file. While JSF has limited built in
Validations.
* The Struts controller can do things like access control on each Action based on user roles. This functionality is not
provided by JSF.
* Only one instance is created for ActionServlet, RequestProcessor, Action.
* We can replace ActionServlet & RequestProcessor class with our own class.
* ActionForm class Object creation One per Session / Request when scope is Session / Request.
Struts Controller Layer:
Following are various components of Struts Controller Layer.
A) ActionServlet
B) RequestProcessor
C) Actions
ActionServlet:ActionSerlvet is the Controller Servlet which is responsible for the following.
1) Initializing Struts Configuration document
2) Receiving request and delegating to RequestProcessor
2)RequestProcessor :RequesrProcessor is responsible for receiving the request, processing the request completely and delivers the response
to client.
RequestProcessor will do the following tasks while processing the request.
1)
2)
3)
4)
5)
request.getrequestURI()
ActionMapping processMapping(HttpServletRequest req,HttpServletResponse res,URI)
ActionForm processActionForm(HttpServletRequest req,HttpServletResponse res,ActionMapping)
void processPopulate(HttpServletRequest req,HttpServletResponse res,ActionForm,ActionMapping)
boolean processValidate(HttpServletRequest req,HttpServletResponse res,ActionForm,ActionMapping)
Action
Dispatch Action
Lookup Dispatch Action
Mapping Dispatch Action
IncludeAction
ForwardAction
switch Action
LocaleAction
DownloadAction
ActionServlet :
import org.apache.struts.action.ActionServlet;
public class ActionServlet extends HttpServlet{}
ActionServlet provides the "controller" in the MVC design pattern for web applications that is commonly
known as "Model 2".
ActionServlet is responsible for initializing Struts Configuration document (sturts-config.xml).
Receiving the request and delegating to RequestProcessor.
RequestProcessor :
import org.apache.struts.action.RequestProcessor;
public class RequestProcessor extends Object{}
* RequestProcessor contains the processing logic that the ActionServlet performs as it receives each servlet request
from the container.
* RequestProcessor is responsible for receiving the request, processing the request completely and delivers the
response to the client.
* We can customize the request processing behavior by subclassing this class and overriding the method(s) whose
behavior we are interested in changing.
protected ActionMapping processMapping(HttpServletRequest, HttpServletResponse, String)
Select the mapping used to process the selection path for this request.
protected ActionForm processMapping(HttpServletRequest, HttpServletResponse, String)
Select the mapping used to process the selection path for this request.
ActionMapping :
import org.apache.struts.action.ActionMapping;
public class ActionMapping extends ActionConfig{}
* An ActionMapping represents the information that the controller, RequestProcessor, knows about the mapping of a
particular request to an instance of a particular Action class.
* The ActionMapping instance used to select a particular Action is passed on to that Action, thereby providing access
to any custom configuration information included with the ActionMapping object.
ActionForward :
import org.apache.struts.action.ActionForward;
public class ActionForward extends ForwardConfig{}
* An ActionForward represents a destination to which the controller, RequestProcessor, might be directed to perform
a
RequestDispatcher.forward or HttpServletResponse.sendRedirect to, as a result of processing activities of an Action
class.
* Instances of this class may be created dynamically as necessary, or configured in association with an
ActionMapping instance for named
lookup of potentially multiple destinations for a particular mapping instance.
ActionErrors :
import org.apache.struts.action.ActionErrors;
public class ActionErrors extends ActionMessages implements Serializable {}
* A class that encapsulates the error messages being reported by the validate() method of an ActionForm. Validation
errors are either global to the entireActionForm bean they are associated with, or they are specific to a particular
bean property (and, therefore, a particular input field on the corresponding form).
* Each individual error is described by an ActionMessage object, which contains a message key (to be looked up in an
appropriate message resources database), and up to four placeholder arguments used for parametric substitution in
the resulting message.
IMPLEMENTATION NOTE - It is assumed that these objects are created and manipulated only within the context of a
single thread. Therefore, no synchronization is required for access to internal collections.
ActionMessage :
import org.apache.struts.action.ActionMessage;
public class ActionMessage extends Object implements Serializable {}
An encapsulation of an individual message returned by the validate method of an ActionForm, consisting of a
message key (to be used to look up message text in an appropriate message resources database) plus up to four
placeholder objects that can be used for parametric replacement in the message text.
ActionMessages :
import org.apache.struts.action.ActionMessages;
public class ActionMessages extends Object implements Serializable {}
A class that encapsulates messages. Messages can be either global or they are specific to a particular bean property.
Each individual message is described by an ActionMessage object, which contains a message key (to be looked up in
an appropriate message resources database), and up to four placeholder arguments used for parametric substitution
in the resulting message.
IMPLEMENTATION NOTE - It is assumed that these objects are created and manipulated only within the context of
a single thread. Therefore, no synchronization is required for access to internal collections.
import org.apache.struts.action.ActionForm;
class LoginForm extends ActionForm{
public void reset(ActionMapping, HttpServletRequest){}
public ActionErrors validate(ActionMapping, HttpServletRequest){
return errors; // errors is an object of ActionErrors class
}
}
import org.apache.struts.action.Action;
class LoginAction extends Action{
public ActionForward execute(ActionMapping, ActionForm, HttpServletRequest,
HttpServletResponse)throws Exception{
return ActionMapping.findForward(String);
}
}
Web.xml
<web-app>
<display-name>JLC_Lab1</display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class> org.apache.struts.action.ActionServlet </servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml,/WEB-INF/jlcindia-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
11) If matching form bean is found then RequestProcessor takes the Form bean type which is the Form bean
java class.
12) RequestProcessor starts the Form bean lifecycle.
A)
B)
C)
D)
E)
Message Bundles:Message Bundle is nothing but a property file where you can define key-value pairs.
Message Bundle can used to centralize two types of Message.
1) Labels
2) Error Messages by validation
A) Labels :a) Define the Label in Message Bundle
label.sidSearch.sid=Enter Student Id
b) Accessing in JSP
<bean:message key= label.sidSearch.sid/>
B) Error Messages by validation
a) Define the errors in Message Bundle
errors.sidsearch.sid= Student Id is Required
b) Use the key to create the ActionError Object when you are adding ActionError Object to ActionErrors
Object.
errors.add(sid, new ActionError(errors.sidsearch.sid);
c) Accessing in JSO
<html:errors property=sid/> ->it shows errors realeted to sid
<html:errors/>
Form Beans :
Threre are six form beans
1)
2)
3)
4)
5)
6)
ActionForm
DynaActionForm
ValidatorForm
DynaValidatorForm
ValidatorActionForm
.DynaValidatorActionForm
Struts Validation :
Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users
browser as well as on the server side. Struts provides two ways to perform Validations on input data :
1. Basic Validation (through validate() method)
2. Validation Framework Validations.
Basic Validations :when you write the validation logic inside the validate() method of form bean java class
then those are called as Basic validations.
Note:
We can use there validation Framework with
1. ValidatorForm,
2. DynaValidatorForm,
3. ValidatorActionForm,
4. DynaValidatorActionForm
4) To display errors in jsp, use<html:errors/>
Developing Custom Validation
1) Write the java class with the name JLCFieldChecks
2) Write one or more methods required depending on number of custom validations required.
3) Implements the required validation logic inside those methods.
public class JLCFieldChecks{
public boolean validateSID(Object, ValidatorAction, Field, ActionErrors, HttpServletRequest){
// write validation logic.
}
}
4)Register the Custom Validation in validator-rules.xml
--------------------------------------------------------------<form-validation>
<global>
<validator name=sidformat
classname=com.jlcindia.struts. JLCFieldChecks
method= validateSID
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction
org.apache.commons.validator.Field,
org.apache.struts.action.ActionErrors,
javax.servlet.http.HttpServletRequest
msg=errors.sidformat>
</validator>
<validator>
// same for another method
</validator>
</global>
</form-validation>
4) Identify the form and corresponding field validations.
Form name: BidSearchForm
Bid:required,bidformat
Form name:sidSearchForm
Sid:required,sidformat
5) Specify the validation required for various fields in myform-validations.xml
<form name=bidSearchForm>
<field Proeprty=bid depends=required,bidformate>
<arg0 key=BatchId resource=false/>
</field>
</form>
<form name=sidSearchForm>
<field Proeprty=sid depends=required,sidformate>
<arg0 key=StudentId resource=false/>
</field>
</form>
6) Add the required properties in message bundle.
SN
ActionF
orm
DynaActi
onForm
ValidatorFor
m
DynaValidatorF
orm
ValidatorActi
onForm
DynaValidator
ActionForm
Static/Dynamic
Static
Dynamic
Static
Dynamic
Static
Dynamic
Fields declaration in
class
YES
NO
YES
NO
YES
NO
Fields declaration in
XML
NO
YES
NO
YES
NO
YES
reset() method
YES
NO(initial
attribute)
YES
NO(initial
attribute)
YES
NO(initial
attribute)
Validate() method
YES
NO
YES
NO
YES
NO
Validations
Basic
Validati
ons
NA
Basic and VF
Validations
VF Validations
Basic and VF
Validations
VF Validations
Validation Binding
NA
NA
Form bean
name
Form bean
name
Action path
value
Action path
value
1
2
3
4
5
6
Tiles Framework :
<plug-in className="org.apache.struts.tiles.TilesPlugin">
<set-property value="WEB-INF/tiles.xml" property="definitions-config"/>
</plug-in>
tiles.xml should be in WIB-INF folder and will contain various Tiles Definitions.
<tiles-definitions>
<definition name= >
</tiles-definitions>
Tiles Framework is mainly a Layout design framework which allows you to centerlize the web page
Layouts,text formats,styles required etc
name=sidForm
type=org.springframework.web.struts.DelegatingActionProxy
input=/sidSearch.jsp/>
<plug-in className=org.springframework.web.struts.ContextLoaderPlugIn>
<set-property property=contextConfigLocation
value=/WEB-INF/studentContext.xml/>
</plug-in>
* in studentContex.xml (Spring Configuration)
<beans>
<bean name=/sidSubmit class=com.jlcindia.struts.SidSearchAction>
<property name=>
<ref bean=/>
</property>
</bean>
</beans>
Note : DelegatingActionProxy is class extends from Action class.
In this above example - type=org.springframework.web.struts.DelegatingActionProxy
Because of this configuration, RP invokes always execute() method of DelegatingActionProxy class for any incoming
request URI. DelegatingActionProxy is responsible for looking up the spring container to find Action class instance
whose name is same as incoming request URI.
* In a Struts application Model Class interacts with database.
* Bean:message is to display message from .propertiesfile. Bean:write this tag is used to output bean property value from
bean property.
How RequestProcessor decides that validation is success or fail?
Based on ActionErrors instance returned by Formbean java class validate().
* Request processor`s processActionForm() instantiates Frombean java class.
What scope is applied to Frombean?
Request or session, depending upon what you selected while creating Formbean. Default Frombean scope is session.
What is the difference between ActionForm and DynaActionForm?
To get the data from user entered text fields we use Form bean concept in Struts. While using form bean, you need to create a
java class with few setters and getter and that class need to be extended from ActionForm. While using DynaActionForm
you no need to write a java class directly you can get the user details without including setter and getter methods.
Can you explain the directory structure for a struts folder in brief ?
Answers : Below are the folders from point of view of root folder.
3
META-INF: - This directory has the Meta information.
WEB-INF/classes: - This location has the actual JAVA classes.
WEB-INF/classes/ApplicationResources.properties:- Contains text which application can
use. For instance error messages.
WEB-INF/lib/struts.jar:- Contains the Struts servlet, helper classes, taglib code etc.
WEB-INF/*.tld:- The Struts tag libraries.
WEB-INF/struts-config.xml:- A Struts configuration file.
WEB-INF/web.xml:- Configuration file for the servlet container
Index.jsp:- All JSP files come in the root directory as this one Index.jsp.
ActionServlet?
ActionServlet is a simple servlet which is the backbone of all Struts applications. It is the main Controller component that
handles client requests and determines which Action will process each received request. It serves as an Action factory
creating specific Action classes based on users request.
7.What is role of ActionServlet?
LookupDispatchAction
reset(): reset() method is called by Struts Framework with each request that uses the defined ActionForm. The purpose of
this method is to reset all of the ActionForm's data members prior to the new request values being set.
Example :
public void reset(ActionMapping mapping, HttpServletRequest request) {
this.password = null;
this.username = null;
}
Question 8: How you will make available any Message Resources Definitions file to the Struts Framework
Environment?
Ans: Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in
the struts project. Message Resources Definitions files can be added to the struts-config.xml file through < messageresources / > tag. Example: < message-resources parameter= MessageResources / >
Message resource definition files can available to the struts environment in two ways
1. using web.xml as
<servlet>
<servlet-name>action<servlet-name>
servlet-class>org.apache.struts.action.ActionServlet<servlet-class>
<init-param>
<param-name>application<param-name>
<param-value>resource.Application<param-value>
</servlet>
2.
<message-resource key="myResorce" parameter="resource.Application" null="false">
Q: What is Action Class?
A: The Action Class is part of the Model and is a wrapper around the business logic. The purpose of Action Class is to
translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute()
method. In the Action Class all the database/business processing are done. It is advisable to perform all the database related
stuffs in the Action Class. The ActionServlet (commad) passes the parameterized class to Action Form using the execute()
method. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the
request to the file as per the value of the returned ActionForward object.
1.What is MVC?
Model-View-Controller (MVC) is a design pattern put together to help control change. MVC decouples interface
from business logic and data.
Model : The model contains the core of the application's functionality. The model encapsulates the state of
the application. Sometimes the only functionality it contains is state. It knows nothing about the view or
controller.
View: The view provides the presentation of the model. It is the look of the application. The view can
access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the
controller. The view should be notified when changes to the model occur.
Controller:The controller reacts to the user input. It creates and sets the model.
6.What is ActionServlet?
ActionServlet is a simple servlet which is the backbone of all Struts applications. It is the main Controller
component that handles client requests and determines which Action will process each received request. It serves
as an Action factory creating specific Action classes based on users request.
7.What is role of ActionServlet?
ActionServlet performs the role of Controller:
Process user requests
Determine what the user is trying to achieve according to the request
Pull data from the model (if necessary) to be given to the appropriate view,
Select the proper view to respond to the user
Delegates most of this grunt work to Action classes
Is responsible for initialization and clean-up of resources
8.What is the ActionForm?
ActionForm is javabean which represents the form inputs containing the request parameters from the View
referencing the Action bean.
9.What are the important methods of ActionForm?
The important methods of ActionForm are : validate() & reset().
10.Describe validate() and reset() methods ?
validate() : Used to validate properties after they have been populated; Called before FormBean is handed to
Action. Returns a collection of ActionError as ActionErrors. Following is the method signature for
thevalidate() method.
public ActionErrors validate(ActionMapping mapping,HttpServletRequest request)
reset(): reset() method is called by Struts Framework with each request that uses the defined ActionForm. The
purpose of this method is to reset all of the ActionForm's data members prior to the new request values being set.
public void reset() {}
11.What is ActionMapping?
Action mapping contains all the deployment information for a particular Action bean. This class is to determine
where the results of the Action will be sent once its processing is complete.
12.How is the Action Mapping specified ?
We can specify the action mapping in the configuration file called struts-config.xml. Struts framework
creates ActionMapping object from <ActionMapping> configuration element of struts-config.xml file
<action-mappings>
<action path="/submit"
type="submit.SubmitAction"
name="submitForm"
input="/submit.jsp"
scope="request"
validate="true">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>
org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>
/WEB-INF/struts-config.xml,
/WEB-INF/struts-admin.xml,
/WEB-INF/struts-config-forms.xml
</param-value>
</init-param>
.....
<servlet>
18.What is the difference between session scope and request scope when saving formbean ?
when the scope is request,the values of formbean would be available for the current request.
when the scope is session,the values of formbean would be available throughout the session.
19.What are the important tags of struts-config.xml ?
The five important sections are:
DispatchAction Example
23.What is the use of ForwardAction?
The ForwardAction class is useful when youre trying to integrate Struts into an existing application that uses
Servlets to perform business logic functions. You can use this class to take advantage of the Struts controller and
its functionality, without having to rewrite the existing Servlets. Use ForwardAction to forward a request to
another resource in your application, such as a Servlet that already does business logic processing or even another
JSP page. By using this predefined action, you dont have to write your own Action class. You just have to set up
thestruts-config file properly to use ForwardAction.
24.What is IncludeAction?
The IncludeAction class is useful when you want to integrate Struts into an application that uses Servlets. Use the
IncludeAction class to include another resource in the response to the request being processed.
25.What is the difference between ForwardAction and IncludeAction?
The difference is that you need to use the IncludeAction only if the action is going to be included by another
action or jsp. Use ForwardAction to forward a request to another resource in your application, such as a Servlet
that already does business logic processing or even another JSP page.
26.What is LookupDispatchAction?
The LookupDispatchAction is a subclass of DispatchAction. It does a reverse lookup on the resource bundle to get
the key and then gets the method whose name is associated with the key into the Resource Bundle.
27.What is the use of LookupDispatchAction?
LookupDispatchAction is useful if the method name in the Action is not driven by its name in the front end, but by
the Locale independent key into the resource bundle. Since the key is always the same, the LookupDispatchAction
shields your application from the side effects of I18N.
28.What is difference between LookupDispatchAction and DispatchAction?
The difference between LookupDispatchAction and DispatchAction is that the actual method that gets called in
LookupDispatchAction is based on a lookup of a key value instead of specifying the method name directly.
29.What is SwitchAction?
The SwitchAction class provides a means to switch from a resource in one module to another resource in a
different module. SwitchAction is useful only if you have multiple modules in your Struts application. The
SwitchAction class can be used as is, without extending.
30.What if <action> element has <forward> declaration with same name as global forward?
In this case the global forward is not used. Instead the <action> elements<forward> takes precendence.
31.What is DynaActionForm?
A specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of properties
(configured in configuration file), without requiring the developer to create a Java class for each type of form
bean.
32.What are the steps need to use DynaActionForm?
Using a DynaActionForm instead of a custom subclass of ActionForm is relatively straightforward. You need to
make changes in two places:
In struts-config.xml: change your <form-bean> to be anorg.apache.struts.action.DynaActionForm instead
of some subclass of ActionForm
<form-bean name="loginForm"type="org.apache.struts.action.DynaActionForm" >
<form-property name="userName" type="java.lang.String"/>
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
public class DynaActionFormExample extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaActionForm loginForm = (DynaActionForm) form;
ActionMessages errors = new ActionMessages();
if (((String) loginForm.get("userName")).equals("")) {
errors.add("userName", new ActionMessage(
"error.userName.required"));
}
if (((String) loginForm.get("password")).equals("")) {
errors.add("password", new ActionMessage(
"error.password.required"));
}
...........
33.How to display validation errors on jsp page?
<html:errors/> tag displays all the errors. <html:errors/> iterates over ActionErrors request attribute.
34.What are the various Struts tag libraries?
The various Struts tag libraries are:
HTML Tags
Bean Tags
Logic Tags
Template Tags
Nested Tags
Tiles Tags
35.What is the use of <logic:iterate>?
<logic:iterate> repeats the nested body content of this tag over a specified collection.
<table border=1>
<logic:iterate id="customer" name="customers">
<tr>
<td><bean:write name="customer" property="firstName"/></td>
<td><bean:write name="customer" property="lastName"/></td>
<td><bean:write name="customer" property="address"/></td>
</tr>
</logic:iterate>
</table>
36.What are differences between <bean:message> and <bean:write>
<bean:message>: is used to retrive keyed values from resource bundle. It also supports the ability to include
parameters that can be substituted for defined placeholders in the retrieved string.
<bean:message key="prompt.customer.firstname"/>
<bean:write>: is used to retrieve and print the value of the bean property. <bean:write> has no body.
<bean:write name="customer" property="firstName"/>
37.How the exceptions are handled in struts?
Exceptions in Struts are handled in two ways:
Programmatic exception handling :
Explicit try/catch blocks in any code that can throw exception. It works well when custom value (i.e., of
variable) needed when error occurs.
Declarative exception handling :You can either define <global-exceptions> handling tags in yourstrutsconfig.xml or define the exception handling tags within <action></action> tag. It works well when custom
page needed when error occurs. This approach applies only to exceptions thrown by Actions.
<global-exceptions>
<exception key="some.key"
type="java.lang.NullPointerException"
path="/WEB-INF/errors/null.jsp"/>
</global-exceptions>
or
<exception key="some.key"
type="package.SomeException"
path="/WEB-INF/somepage.jsp"/>
38.What is difference between ActionForm and DynaActionForm?
An ActionForm represents an HTML form that the user interacts with over one or more pages. You will
provide properties to hold the state of the form with getters and setters to access them. Whereas,
usingDynaActionForm there is no need of providing properties to hold the state. Instead these properties
and their type are declared in the struts-config.xml
The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as
the Struts Config file grow larger.
The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time
checking for the form fields. Detecting them at runtime is painful and makes you go through redeployment.
ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.
ActionForm were designed to act as a Firewall between HTTP and the Action classes, i.e. isolate and
encapsulate the HTTP request parameters from direct use in Actions. With DynaActionForm, the property
access is no different than using request.getParameter( .. ).
DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that
can be avoided.
39.How can we make message resources definitions file available to the Struts framework environment?
We can make message resources definitions file (properties file) available to Struts framework environment by
adding this file tostruts-config.xml.
<message-resources parameter="com.login.struts.ApplicationResources"/>
40.What is the life cycle of ActionForm?
The lifecycle of ActionForm invoked by the RequestProcessor is as follows:
Retrieve or Create Form Bean associated with Action
"Store" FormBean in appropriate scope (request or session)
Reset the properties of the FormBean
Populate the properties of the FormBean
Validate the properties of the FormBean
Pass FormBean to Action
Struts
Q 1. What is MVC?
Model-View-Controller (MVC) is a design pattern put together to help control change. MVC decouples interface from
business logic and data.
Model: The model contains the core of the application's functionality. The model enca psulates the state of the application.
Sometimes the only functionality it contains is state. It knows nothing about the view or controller.
View: The view provides the presentation of the model. It is the look of the application. The view can access the model
getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified
when changes to the model occur.
Controller: The controller reacts to the user input. It creates and sets the model.
Q 2. What is a framework?
Framework is made up of the set of classes which allow us to use a library y in a best possible way for a specific
requirement.
Q 3. What is Struts framework?
Struts framework is an open-source framework for developing the web applications in Java EE, based on MVC-2
architecture. It uses and extends the Java Servlet API. Struts is robust architecture and can be used for the development of
application
of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java. Struts provides
its own Controller component and integrates with other technologies to provide the Model and the View. For the Model,
Struts can interact with standard data access technologies, like JDBC and EJB, as well as most any third-party packages, like
Hibernate, iBATIS, or Object Relational Bridge. For the View, Struts works well with JavaServer Pages, including JSTL and
JSF, as well as Velocity Templates, XSLT, and other presentation systems.
Q 4. What is Jakarta Struts Framework?
Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based
applications. Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts
framework makes it much easier to design scalable, reliable Web applications with Java.
Q 5. What is ActionServlet?
The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this
class plays the role of controller. All the requests to the server
goes through the controller. Controller is responsible for handling all the requests.
Q 6. What is role of ActionServlet?
ActionServlet performs the role of Controller:
Action class has a return type org.apache. struts.action.ActionForward class. The ActionForward class represents a
destination to which the controller may send control once an action has completed. Instead of specifying an actual JSP page
in the code, you can declaratively associate as action forward through out the application. The action forward are specified in
the configuration file.
<action>
path= "/somerequest"
type="com.somepackage.someAction"
scope="request"
name="someForm"
validate="true"
input="somejsp.jsp"
<forward name="Success" path="/action/xys" redirect="true"/>
<forward name="Failure" path="/somejsp.jsp" redirect="true"/>
</action>
The action forward mappings also can be specified in a global section, independent of any specific action mapping.
<global-forwards>
<forward name="Success" path="/action/somejsp.jsp" />
<forward name="Failure" path="/someotherjsp.jsp" />
</global-forwards>
Q13. How you will handle exceptions in Struts?
In Struts you can handle the exceptions in two ways:
a) Declarative Exception Handling: You can either define global exception handling tags in your struts-config.xml or
define the exception handling tags within
<action>..</action> tag.
Example:
<exception
key="database.error.duplicate"
path="/UserExists.jsp"
type="mybank.account.DuplicateUserException"/>
b) Programmatic Exception Handling: Here you can use try{}catch{} block to handle the exception.
Q14. What are the different kinds of actions in Struts?
The different kinds of actions in Struts are:
ForwardAction, IncludeAction, DispatchAction, LookupDispatchAction, SwitchAction
Q15. What is DispatchAction?
The DispatchAction class is used to group related actions into one class. Using this class, you can have a method for
each logical action compared than a single execute method. The DispatchAction dispatches to one of the logical actions
represented by the methods. It picks a method to invoke based on an incoming request parameter. The value of the incoming
parameter is the name of the method that the DispatchAction will invoke.
Q16. How to use DispatchAction?
To use the DispatchAction, follow these steps :
1. Create a class that extends DispatchAction (instead of Action)
2. In a new class, add a method for every function you need to perform on the service The method has the same
signature as the execute() method of an Action class.
3. Do not override execute() method Because DispatchAction class itself provides execute() method.
4. Add an entry to struts-config.xml
Q17. What is LookupDispatchAction?
The LookupDispatchAction is a subclass of DispatchAction. It does a reverse lookup on the resource bundle to get the key
and then gets the method whose name is associated with the key into the Resource Bundle.
Q18. What is the use of LookupDispatchAction?
LookupDispatchAction is useful if the method name in the Action is not driven by its name in the front end, but by the
Locale independent key into the resource bundle. Since the key is always the same, the LookupDispatchAction shields your
application from the side effects of I18N.
Q19. What is difference between LookupDispatchAction and DispatchAction?
The difference between LookupDispatchAction and DispatchAction is that the actual method that gets called in
LookupDispatchAction is based on a lookup of a key value instead of specifying the method name directly.
Q20. What is SwitchAction?
The SwitchAction class provides a means to switch from a resource in one module to another resource in a different module.
SwitchAction is useful only if you have multiple modules in your Struts application. The SwitchAction class can be used as
is, without extending.
Q21. What if <action> element has <forward> declaration with same name as global forward?
In this case the global forward is not used. Instead the <action> elements <forward> takes precendence.
Q22. What is difference between ActionForm and DynaActionForm?
An ActionForm represents an HTML form that the user interacts with over one or more pages. You will provide properties to
hold the state of the form with getters and setters to access them. Whereas, using DynaActionForm there is no need of
providing properties to hold the state. Instead these properties and their type are declared in the struts-config.xml.
The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config
file grow larger.
The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time checking for the form
fields. Detecting them at runtime is painful and makes you go through redeployment.
ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.
ActionForm were designed to act as a Firewall between HTTP and the Action classes, i.e. isolate and encapsulate the HTTP
request parameters from direct use in Actions. With DynaActionForm, the property access is no different than using
request.get Parameter( .. ).
DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be
avoided.
</global-forwards>
<!-- ========== Action Mapping Definitions ======== -->
<action-mappings>
<action
path="/login"
type="LoginAction" >
</action>
</action-mappings>
<!-- ========== Properties Definitions ============ -->
<message-resources parameter="MessageResources" />
<!-- ========== Validator framework Definitions ============ -->
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property
property="pathnames"
value="/org/apache/struts/validator/validator-rules.xml,
/WEB-INF/validation.xml"/>
</plug-in>
</struts-config>
Q25. What are the core classes of the Struts Framework?
A: Core classes of Struts Framework are ActionForm, Action, ActionMapping, Action Forward, ActionServlet etc.
Q26. What is action mappings?
An action mapping is a configuration file entry that, in general, associates an action name with an action. An action
mapping can contain a reference to a form bean that the action can use, and can additionally define a list of local forwards
that is visible only to this action.
Q27. Describe validate() and reset() methods ?
validate () and reset() methods defined inActionForm class.
validate() : Used to validate properties after they have been populated; Called before FormBean is handed to Action. Returns
a collection of ActionMessage as ActionErrors. Following is the method signature for the validate() method.
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request)
reset(): reset() method is called by Struts Framework with each request that uses the defined ActionForm. The purpose of
this method is to reset all of the ActionForm's data members prior to the new request values being set.
public void reset() {}
Q28. Give the Details of XML files used in Validator Framework?
The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validatorrules.xmldefines the standard validation routines, these are reusable and used in validation.xml. to define the form specific
validations. The validation.xml defines the validations applied to a form bean.
Q29. How you will enable front-end validation based on the xml in validation.xml?
The <html:javascript> tag to allow front-end validation based on the xml in validation.xml. For example the code:
<html:javascript formName="logonForm" dynamicJavascript="true" staticJavascript="true" /> generates the client side java
script for the form "logonForm" as defined in the validation.xml file. The <html:javascript> when added in the jsp file
generates the client site validation script.
Q30. What is the difference between perform() and execute() methods?
perform() method defined in Struts 1.0. but it is was deprecated in the Struts Version 1.1. In Struts 1.x, Action.perform() is
the method called by the ActionServlet. This is typically where your business logic resides, or at least the flow control to
your JavaBeans and EJBs that handle your business logic. As we already mentioned, to support declarative exception
handling, the method signature changed in perform. Now execute just throws Exception. Action.perform() is now
deprecated; however, the Struts v1.1 ActionServlet is smart enough to know whether or not it should call perform or execute
in the Action, depending on which one is available.
Q31. What are the various Struts tag libraries?
Struts is very rich framework and it provides very good and user friendly way to develop web application forms. Struts
provide many tag libraries to ease the development of web applications. These tag libraries are:
* Bean tag library - Tags for accessing JavaBeans and their properties.
* HTML tag library - Tags to output standard HTML, including forms, text boxes, checkboxes, radio buttons etc..
* Logic tag library - Tags for generating conditional output, iteration capabilities and flow management
* Tiles or Template tag library - For the application using tiles
* Nested tag library - For using the nested beans in the application
Q32. What are the difference between <bean:message> and <bean:write>?
<bean:message>: This tag is used to output locale-specific text (from the properties files) from a MessageResources bundle.
<bean:write>: This tag is used to output property values from a bean. <bean:write> is a commonly used tag which enables
the programmers to easily present the data.
Q33. What are difference between ActionErrors and ActionMessage?
ActionMessage: A class that encapsulates messages. Messages can be either global or they are specific to a particular
bean property.
Each individual message is described by an ActionMessage object, which contains a message key (to be looked up in an
appropriate message resources database), and up to four placeholder arguments used for parametric substitution in the
resulting message.
ActionErrors: A class that encapsulates the error messages being reported by the validate() method of an ActionForm.
Validation errors are either global to the entire ActionForm bean they are associated with, or they are specific to a particular
bean property (and, therefore, a particular input field on the corresponding form).
Q34. What is the use of ForwardAction?
The ForwardAction class is useful when youre trying to integrate Struts into an existing application that uses Servlets to
perform business logic functions. You can use this class to take advantage of the Struts controller and its functionality,
without having to rewrite the existing Servlets. Use ForwardAction to forward a request to another resource in your
application, such as a Servlet that already does business logic processing or even another JSP page. By using this predefined
action, you dont have to write your own Action class. You just have to set up the struts-config file properly to use
ForwardAction.
Q35. What is IncludeAction?
The IncludeAction class is useful when you want to integrate Struts into an application that uses Servlets. Use the
IncludeAction class to include another resource in the response to the request being processed.
Q36. What are the steps need to use DynaActionForm?
Using a DynaActionForm instead of a custom subclass of ActionForm is relatively straightforward. You need to make
changes in two places:
In struts-config.xml: change your <form-bean> to be an org.apache.struts.action.Dyna ActionForm instead of some subclass
of ActionForm
<form-bean name="loginForm"
type="org.apache.struts.action.DynaActionForm" >
<form-property name="userName" type="java.lang.String"/>
<form-property name="password" type="java.lang.String" />
</form-bean>
In your Action subclass that uses your form bean:
o import org.apache.struts.action.DynaActionForm
o downcast the ActionForm parameter in execute() to a DynaActionForm
o access the form fields with get(field) rather than getField()