You are on page 1of 32

What is Struts

:
* 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) request.getrequestURI()
2) ActionMapping processMapping(HttpServletRequest req,HttpServletResponse res,URI)
3) ActionForm processActionForm(HttpServletRequest req,HttpServletResponse res,ActionMapping)
4) void processPopulate(HttpServletRequest req,HttpServletResponse res,ActionForm,ActionMapping)
5) boolean processValidate(HttpServletRequest req,HttpServletResponse res,ActionForm,ActionMapping)

6) Action processActionCreate(HttpServletRequest req,HttpServletResponse res,ActionMapping)
7) ActionForward processActionPerform(HttpServletRequest req,HttpServletResponse res,Action,ActionForm,
ActionMapping)
8) ActionForward processException(HttpServletRequest req,HttpServletResponse res,Exception,ActionForm,
ActionMapping)
Or
boolean processForward(HttpServletRequest req,HttpServletResponse res,ActionMapping)

3)Actions :-

Action is the last component in the controller layer from where business layer starts.
Action class you are writing may be subclass of one the following built-in Actions.

1. Action
2. Dispatch Action
3. Lookup Dispatch Action
4. Mapping Dispatch Action
5. IncludeAction
6. ForwardAction
7. switch Action
8. LocaleAction
9. 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>

LoginForm"/> </form-beans> <global-exceptions> <exception key="errors.jsp"> .apache.ActionServlet </servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.BatchIDNotFoundException"/> </global-exceptions> <global-forwards> <forward name="success" path="/home.LoginAction" scope="request" validate="true" input="/login.jlcindia.struts.bidsearch.jps" type="com./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>*.xml (place in /WEB-INF folder) <struts-config> <data-sources> <data-source></data-source> </data-sources> <form-beans> <form-bean name="loginForm" type="com.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>action</servlet-name> <servlet-class> org.notfound" path="/bidSearch.<welcome-file>login.bid.jlcindia.action.do</url-pattern> </servlet-mapping> </web-app> struts-config.jsp"/> </global-forwards> <action-mappings> <action path="/loginSubmit" name="loginForm" type="com.xml.jlcindia.

6) RequestProcessor checks whether any <action> tag is available in struts config. 9) RequestProcessor checks whether any <form-bean> tag is available in struts-config.xml” property=”definitions-config”/> </plug-in> </plug-in> </struts-config> Struts Request Processing Flow:-> (stuts flow) When I start the Server after deploying struts based web application. 3) If any errors found while parsing xml then ActionServlet will not be initialized and not ready to serve the requests. 2) Init() method is responsible for parsing the Data(reading the data) from Struts configuration document. 2) If the requested Resource is not available then error message will be given with Http status code:404 3) If the requested Resource is available then Request processor checks whether that Resource ( JSP) contains any <html:form > tag. /WEB-INF/myform-validations.apache.tiles. A) Container invokes the service() method of ActionServlet.struts. (500: cannot retrieve mapping for action/LoginSubmit1) 8) If matching action is found then RequestProcessor takes form bean name.struts.apache.xml whose path attribute value is same as action attribute value.html. 1) RequestProcessor checks whether the requested Resource is available or not. then following tasks will happen at container start up.action.BEAN in any scope) 5) If the identified resource contains <html:form> tag then takes the RequestURI(action attribute value).ValidatorPlugIn"> <set-property value="/WEB-INF/validator-rules. B) ActionServlet delegates the request to RequestProcessor. 10) If No matching form bean is found then error message will be given. 4) If the identified resource does not contain any <html:form> tag then error message will be given (500:cannot find bean org.jlcindia. 4) If no errors found while parsing xml then ActionServlet will be initialized and ready to Serve the requests with url-pattern *.xml" property="pathnames"/> <plug-in className=”org.detail) D) Invokes the init() method by passing ServletConfig object as parameter.taglib.xml.struts.apache.validator.do When you request for resource (login.struts.MyMessage"/> <plug-in className="org. (500: cannot retrieve definition for form bean loginForm) . C) RequestProcessor starts the processing of given request by doing the following tasks.jsp) then following things will happen.ActionServlet) B) Creates the ActionServlet class instance.Tilesplugin”> <set-property value=”/WEB-INF/tiles.xml whose name attribute value is same as action name attribute value. 1) Container initializes the ActionServlet because of <load-on-startup> A) Loads the ActionServlet class(org. 7) If No matching action is found then error message will be given.apache.<forward name=”” path=””/> <exception key=”” type=”” path=””/> </action> </action-mappings> <controller/> <message-resources parameter="com. C) Creates the ServletConfig object and initializes the ServletConfig object with init parameters (config.debug.

Calls the reset() method. 12) RequestProcessor starts the Form bean lifecycle. (500:cannot retrieve mapping for action/LoginSubmit1). A. RequestProcessor takes the RequestURI(action attribute value) 2. Invokes the validate() method. 11) If matching form bean is found then RequestProcessor takes the Form bean type which is the Form bean java class. 8. If ActionErrors object does not contain any ActionError objects the RequestProcessor takes action type. b. 1. A) Loads the Form bean java class B) Creates the Form bean java class object by calling default constructor. Collects the data from client submitted request and stores the Form bean object by calling setter methods. 4. Creates or retrieves the Action class object.xml whose path attribute value is same as action attributes value 3. f. If No matching action is found then error message will be given. RequestProcessor starts the Form bean lifecycle. 9. RequestProcessor identifies the JSP related to ActionForward object returned or Exception thrown by execute() method. d. 12. 13. Identified JSP will be rendered to Client. C. C) Stores the Form bean object in the given scope (default scope is session) D) Calls the reset() method (it is used to set the default values). 6. 10. . e. ActionServlet delegates the request to RequestProcessor. Handling Exception thrown by Action class:- Steps:- 1) Write the Required User-defined Exception Class BatchIDNotFoundException extends Exception{ } 2) throw that User-defined Exception in any Action class throw new BatchIDNotFoundException(). B. 11. 5. RequestProcessor checks whether any <action> tag is available in sturts-config. 13) Identified resource will be rendered to client. c. a. If matching form bean is found then RequestProcessor takes the Form bean type which is the Form bean java class. Execute() method may return ActionForward object on the successful completion or Exception. Container invokes the service() method of ActionServlet. If No matching form bean is found then error message will be given. Creates or retrieves the Form bean object. If ActionErrors object contains any ActionError objects then takes the input jsp and forwards to client with error messages. RequestProcessor starts the processing of given request by doing the following tasks.xml whose name attribute value is same as action name attribute value. If matching action is found then RequestProcessor takes form bean name. When you submit the Form(login. E) Collects the data from Form bean object by calling getter methods and populates that data in jsp form fields.jsp) then following things will happen. (500: cannot retrieve definition for form bean loginForm) 7. Invokes execute() method. a. RequestProcessor checks whether any <form-bean> tag is available in struts-config.

BidSearchForm" /> </form-beans> <action-mappings> <action path="/BidSubmit" name="bidSearchForm" type="com.jsp" /> </action> </action-mappings> <message-resources parameter="com.BidSearchAction" scope="session" validate="true" input="/bidsearch.sid.jsp" key="errors. }else{ try { int x=Integer.add("sid".sidsearch.format2")).xml <struts-config> <form-beans> <form-bean name="bidSearchForm" type="com. errors). write in Form class as follows:- public ActionErrors validate(ActionMapping am. if(sid==null || sid.struts1.sidsearch.new ActionError("errors.length()==0){ errors.length()==0 || p2.BatchIDNotFoundException" path="/bidsearch.jlcindia. }else if(!sid.new ActionError("errors.jlcindia. 5) Display the Error message with <html:errors/> Handling ActionErrors in Action class:- Write the following in Action class:- ActionErrors errors = new ActionErrors().jlcindia.startsWith("JLC-")){ errors.ApplicationResources" /> </struts-config> 4) add the key in property file errors. }}} return errors.format2")).add("sid".struts1.sidsearch.format1")).add("sid".saveErrors(req. errors. } Struts Layers:- .required")).parseInt(p2).notfound" /> <forward name="bidsearch" path="/bidsearch.new ActionError("errors. 3) configure the following <exception> in struts-config.sidsearch.notfound=Student Not Found.bidsearch.bidsearch.sid.notfound")).HttpServletRequest req){ ActionErrors errors=new ActionErrors().new ActionError("errors.add("sid".add("sid".bid.sid.substring(4).jsp"> <exception type="com. new ActionError("errors. if(p2.bid. } catch (Exception e) { errors.struts1.sid.struts1. this.sidsearch.sid. }else{ String p2=sid.jlcindia.length()>4){ errors.

add(“sid”.sid”/> B) Error Messages by validation a) Define the errors in Message Bundle errors. You can use any thing in model layer as per your requirement.sidsearch. 1) HTML Tag Library 2) Bean Tag Library 3) Logic Tag Library 4) Tiles Tag Library 5) Nested Tag Library 6) Template Tag Library Message Bundles:- Message Bundle is nothing but a property file where you can define key-value pairs. c) Accessing in JSO <html:errors property=”sid”/> ->it shows errors realeted to sid <html:errors/> -> it shows all errors . errors. Struts does not specify or force any rules related to model layer.sidSearch. 1) JSP element 2) EL (expression language) 3) JSTL 4) Struts Tag Library 5) Message Bundles 6) Form Beans Struts Tag Library :- Threre are six tag libraries provided.sidsearch. Message Bundle can used to centralize two types of Message.sidSearch.sid=Enter Student Id b) Accessing in JSP <bean:message key= “label.sid”). Struts Presentation Layer:- You can implement the following components in the presentation layer of sturts application.Struts mainly deals with presentation layer and Controller layer.sid= Student Id is Required b) Use the key to create the ActionError Object when you are adding ActionError Object to ActionErrors Object. new ActionError(“errors. 1) Labels 2) Error Messages by validation A) Labels :- a) Define the Label in Message Bundle label.

struts. The key passed into the validator is the action element's 'name' attribute from the struts-config. Struts provides two ways to perform Validations on input data : 1.xml.apache. Basic Validations :- when you write the validation logic inside the validate() method of form bean java class then those are called as Basic validations.DynaValidatorForm.validator.DynaActionForm.xml which should match the form element's name attribute in the validation.ActionForm. It can be use to validate the data on the users browser as well as on the server side.DynaValidatorActionForm. Struts Validation : Struts Framework provides the functionality to validate the form data.ValidatorForm.action.execute method is called. public class DynaActionForm extends ActionForm implements DynaBean{} Specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of properties. import org.apache.DynaValidatorActionForm Struts Form Bean Class : ---------------------------- import org. Serializable{} This class extends DynaActionForm and provides basic field validation based on an XML file.action. import org. import org. Such a bean will have had its properties initialized from the corresponding request parameters before the corresponding Action.apache.struts. without requiring the developer to create a Java class for each type of form bean.struts. Form Beans : Threre are six form beans 1) ActionForm 2) DynaActionForm 3) ValidatorForm 4) DynaValidatorForm 5) ValidatorActionForm 6) .struts. import org. public abstract class ActionForm extends Object implements Serializable {} An ActionForm is a JavaBean optionally associated with one or more ActionMappings.struts. .apache.struts. The key passed into the validator is the action element's 'name' attribute from the struts-config.ValidatorActionForm.xml which should match the form element's name attribute in the validation.xml which should match the form element's name attribute in the validation.xml.validator. The key passed into the validator is the action element's 'path' attribute from the struts-config.validator. public class DynaValidatorForm extends DynaActionForm implements DynaBean. Basic Validation (through validate() method) 2.apache. public class ValidatorActionForm extends ValidatorForm implements Serializable{} This class extends ValidatorForm and provides basic field validation based on an XML file.apache. Serializable{} This class extends DynaValidatorForm and provides basic field validation based on an XML file.xml which should match the form element's name attribute in the validation. The key passed into the validator is the action element's 'path' attribute from the struts-config. Validation Framework Validations.xml.xml.validator. import org. public class ValidatorForm extends ActionForm implements Serializable{} This class extends ActionForm and provides basic field validation based on an XML file. public class DynaValidatorActionForm extends DynaValidatorForm implements DynaBean.

xml. short.validator. All these built-in validators are registered in validator-rules. public ActionErrors validate(ActionMapping. you must explicitly integrate validation Framework with struts by writing the following <plug-in> in struts-configuration document.apache.required=<font color=red size=5> {0} is required</font> login.minlength. Possible values of validate attribute are true or false. integer. myform-validation. Validation Framework Validations:- Validation Framework Validations is a separate Framework.un=Username 3) Use the correct form bean type Public class LoginForm extends ValidatorForm{ } . byte.maxlength 2) Specify the validations required for various fields of login form in myform-validations.ValidatorPlugIn”> <set-property property=”pathnames” value=”/WEB-INF/validator-rules. Form name:LoginForm Username: required.xml <form name=”loginForm”> <field property=”username” depends=”required”> <arg0 key=”login. HttpServletRequest) validate() method invocation will be depending on validate attribute of <action> tag.xml.struts./WEB-INF/myform- validator. data. For using this we have to integrate like- <plug-in className=”org.xml (use validator-rules. Steps:- 1) Identify the Form and corresponding field validations. If true then validate() method will be called If false the validate() will be not called. validate() method signature must be as follows. minlength. maxlength. email.xml here) – It should be placed in /WEB-INF folder You hava to specify the validations required for various fileds of your form. it is not a part of Struts Framework. float double etc.xml”> </plug-in> validator-rules.maxlength Password:required. minlength. If you want to use validation Framework Validations in struts .un” resource=”true”/> </field> <field property=”password” depends=”required”> <arg0 key=”Password” resource=”false”/> </field> 2) Add the required properties in message bundle errors.xml (3rd Party Rules defined/Registered here) – * it should be placed in /WEB-INF folder * Apache has implemented some commonly required validations called – required. * We can implement our own validation (Custom Validation) and you can register custome validations in validator- rules.xml. long.

ValidatorForm. org. Field.ValidatorAction org. .sidformat 5) Specify the validation required for various fields in myform-validations. HttpServletRequest){ // write validation logic…….struts. ActionErrors. JLCFieldChecks” method=” validateSID” methodParams=”java. 2.xml <form name=”bidSearchForm”> <field Proeprty=”bid” depends=”required.sidformat”> </validator> <validator> // same for another method </validator> </global> </form-validation> 4) Identify the form and corresponding field validations. ValidatorActionForm.servlet. javax.struts.xml --------------------------------------------------------------- <form-validation> <global> <validator name=”sidformat” classname=”com.ActionErrors.lang.action.sidformate”> <arg0 key=”StudentId” resource=”false”/> </field> </form> 6) Add the required properties in message bundle.validator. 3) Implements the required validation logic inside those methods.commons.Field. 3.http. DynaValidatorForm.bidformate”> <arg0 key=”BatchId” resource=”false”/> </field> </form> <form name=”sidSearchForm”> <field Proeprty=”sid” depends=”required.Note: We can use there validation Framework with – 1.commons.apache. ValidatorAction. DynaValidatorActionForm 4) To display errors in jsp.apache.validator. } } 4)Register the Custom Validation in validator-rules. org.apache. 4. 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.jlcindia.Object. Form name: BidSearchForm Bid:required.bidformat Form name:sidSearchForm Sid:required. public class JLCFieldChecks{ public boolean validateSID(Object.HttpServletRequest” msg=”errors.

Public class LoginForm extends ValidatorForm{ } 8) To display errors in jsp. use <html:errors/> Form Bean: Form bean is Container of Data Form bean can be in three scopes. 1) With the client submitted data( RequestProcessor will do automatically) 2) With the data Collected from DB ( you have to do explicitly). Form bean object can be initialized in two ways.xml } If any errors found Request will be forwarded to input jsp }else{ Go to step 6 } }else{ Go to step6 } 6) execute() method will be called. 1) Request 2) Session 3) Application Default scope of a form bean is session. If dynamic form is used then all the fields will be reset to defaults automatically or fields will be initialized with data specified for “initial” attribute of <form-property> tag 4) Collects the clients submitted data and populates into Form bean object 5) If(validate==true){ If(BasicValidation){ Invokes the validate() method overridden by you }else{ Invokes various validatexx() method as per myformvalidations. 3) If static form is used then calls the reset() method. 7) Use the correct form bean type. There are six types of Form beans. 1) ActionForm 2) DynaActionForm 3) ValidatorForm 4) DynaValidatorForm 5) ValidatorActionForm 6) DynaValidatorActionForm These six types can be divided into 2 categories.Validation framework validations . Form Bean LifeCyle: 1) Loads the Form Bean class (one Time) 2) Created or Retrives the Form Bean Object. 1) Static forms 2) Dynamic forms NA-Not Applicable. VF Validations.

x .apache.x.JSF2.x.xml" property="definitions-config"/> </plug-in>  tiles.x.xml <action path=”/sidSubmit” .TilesPlugin"> <set-property value="WEB-INF/tiles. <tiles-definitions> <definition name=”” > </tiles-definitions>  Tiles Framework is mainly a Layout design framework which allows you to centerlize the web page Layouts. * in struts-config. <plug-in className="org. you have to add the following <plug-in> in struts-config.  You have to explicitly integrate Tiles Framework with sturts1.text formats.SpringMVC  You integrate Tile Framework with sturts.xml only ActionServlet will be configured.struts2.xml should be in WIB-INF folder and will contain various Tiles Definitions.tiles.JSF1.struts.styles required etc Struts integration with Spring Framework: -------------------------------------------------- * No Changing in web.SN Form Bean class ActionF DynaActi ValidatorFor DynaValidator ValidatorActi DynaValidator orm onForm m Form onForm ActionForm 1 Static/Dynamic Static Dynamic Static Dynamic Static Dynamic 2 Fields declaration in YES NO YES NO YES NO class 3 Fields declaration in NO YES NO YES NO YES XML 4 reset() method YES NO(initial YES NO(initial YES NO(initial attribute) attribute) attribute) 5 Validate() method YES NO YES NO YES NO 6 Validations Basic NA Basic and VF VF Validations Basic and VF VF Validations Validati Validations Validations ons 7 Validation Binding NA NA Form bean Form bean Action path Action path name name value value Tiles Framework :  Tiles framework is a seprate Framework and is not a part of sturts framework.

* In a Struts application Model Class interacts with database. depending upon what you selected while creating Formbean.struts. Default Frombean scope is session. How RequestProcessor decides that validation is success or fail? Based on ActionErrors instance returned by Formbean java class validate().jlcindia.Contains the Struts servlet. * Bean:message is to display message from .All JSP files come in the root directory as this one Index. Bean:write this tag is used to output bean property value from bean property.xml (Spring Configuration) <beans> <bean name=”/sidSubmit” class=”com. ActionServlet? ActionServlet is a simple servlet which is the backbone of all Struts applications.web. WEB-INF/web. DelegatingActionProxy is responsible for looking up the spring container to find Action class instance whose name is same as incoming request URI. While using DynaActionForm you no need to write a java class directly you can get the user details without including setter and getter methods.tld:.web.struts. What is the difference between ActionForm and DynaActionForm? To get the data from user entered text fields we use Form bean concept in Struts.name=”sidForm” type=”org. you need to create a java class with few setters and getter and that class need to be extended from ActionForm.DelegatingActionProxy” Because of this configuration.jar:. It serves as an Action factory – creating specific Action classes based on user’s request.ContextLoaderPlugIn”> <set-property property=”contextConfigLocation” value=”/WEB-INF/studentContext. WEB-INF/lib/struts. 7.What is role of ActionServlet? .xml:.Contains text which application can use.A Struts configuration file.DelegatingActionProxy” input=”/sidSearch. 3 META-INF: . While using form bean. WEB-INF/struts-config.jsp”/> <plug-in className=”org. taglib code etc.struts.properties:. In this above example .springframework.jsp.Configuration file for the servlet container Index. Can you explain the directory structure for a struts folder in brief ? Answers : Below are the folders from point of view of root folder.springframework.jsp:. What scope is applied to Frombean? Request or session. It is the main Controller component that handles client requests and determines which Action will process each received request.web.xml”/> </plug-in> * in studentContex. For instance error messages.xml:. helper classes.propertiesfile. WEB-INF/classes: . RP invokes always execute() method of DelegatingActionProxy class for any incoming request URI.This directory has the Meta information. WEB-INF/*.type=”org.This location has the actual JAVA classes. WEB-INF/classes/ApplicationResources.struts.springframework.SidSearchAction”> <property name=””> <ref bean=””/> </property> </bean> </beans> Note : ‘DelegatingActionProxy’ is class extends from Action class. * Request processor`s processActionForm() instantiates Frombean java class.The Struts tag libraries.

This means there is no compile time checking for the form fields.  ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.  DynaActionForm Question: What are difference between ActionErrors and ActionMessage? Answer: ActionMessage: A class that encapsulates messages. The process() method of the RequestProcessor uses the template method design pattern.error. isolate and encapsulate the HTTP request parameters from direct use in Actions.duplicate" path="/UserExists.  The DynaActionForm is not strongly typed as the ActionForm.jsp" type="mybank. or they are specific to a particular bean property (and. ActionErrors: A class that encapsulates the error messages being reported by the validate() method of an ActionForm. Instead these properties and their type are declared in thestruts- config.What is difference between ActionForm and DynaActionForm?  An ActionForm represents an HTML form that the user interacts with over one or more pages. Detecting them at runtime is painful and makes you go through redeployment. Example: <exception key="database. Messages can be either global or they are specific to a particular bean property. using DynaActionFormthere is no need of providing properties to hold the state.e. ).account. Validation errors are either global to the entire ActionForm bean they are associated with. and up to four placeholder arguments used for parametric substitution in the resulting message.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..xml or define the exception handling tags within <action>. the property access is no different than using request. Each individual message is described by an ActionMessage object. therefore.xml  The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger. i. Struts controller uses the command design pattern and the action classes use theadapter design pattern.  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 What design patterns are used in Struts? Struts is based on model 2 MVC (Model-View-Controller) architecture.getParameter( . Struts also implement the following J2EE design patterns.  Service to Worker  Dispatcher View  Composite View (Struts Tiles)  Front Controller  View Helper  Synchronizer Token 38.. Whereas. With DynaActionForm.</action> tag.DuplicateUserException"/> .  ActionForm were designed to act as a Firewall between HTTP and the Action classes. which contains a message key (to be looked up in an appropriate message resources database). Question: How you will handle exceptions in Struts? Answer: 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. a particular input field on the corresponding form). You will provide poerties to hold the state of the form with getters and setters to access them.

HttpServletRequest request) { this. to support declarative exception handling. the method signature changed in perform. An action can perform tasks such as validating a user name and password. associates an action name with an action. using Internalization functionality DispatchAction selects the method to execute LookupDispatchAction looks into the depending on the request parameter value resource bundle file and find out the which is configured in the xml file. Dispatch Action LookupDispatchAction It’s a parent class of LookupDispatchAction Subclass of Dispatch Action DispatchAction provides a mechanism for An abstract Action that dispatches to the grouping a set of related functions into a single subclass mapped executes method. and can additionally define a list of local forwards that is visible only to this action. however.action. An action servlet must be an instance of an org. corresponding key name. or at least the flow control to your JavaBeans and EJBs that handle your business logic. Example : public void reset(ActionMapping mapping. thus eliminating the need to create useful in cases where an HTML form has separate actions for each function.password = null. which implements a portion of a Web application and whose perform or execute method returns a forward. An action mapping can contain a reference to a form bean that the action can use. } 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.xml file through < message- resources / > tag. Action.apache.perform() is the method called by the ActionServlet. The servlet receives a forward from the action and asks the servlet container to pass the request to the forward's URL. DispatchAction is not useful for I18N LookupDispatchAction is used for I18N reset(): reset() method is called by Struts Framework with each request that uses the defined ActionForm. Example: < message-resources parameter= MessageResources / > .b) Programmatic Exception Handling: Here you can use try{}catch{} block to handle the exception. in general. Message Resources Definitions files can be added to the struts-config.ActionServlet class or of a subclass of that class. As we already mentioned.perform() is now deprecated. We can map this key name to a method name by overriding the getKeyMethodMap() method. This is typically where your business logic resides.username = null. The purpose of this method is to reset all of the ActionForm's data members prior to the new request values being set. Question: What is the difference between perform() and execute() methods? Answer: Perform method is the method which was deprecated in the Struts Version 1. An action mapping is a configuration file entry that. this. Question: What is Struts actions and action mappings? Answer: A Struts action is an instance of a subclass of an Action class. If not using Internalization functionality then Lookup Dispatch Action is useful when we are dispatch action is more useful.1. An action servlet is a servlet that is started by the servlet container of a Web server to process a request that invokes an action. Action. Now execute just throws Exception.struts.x.1 ActionServlet is smart enough to know whether or not it should call perform or execute in the Action. This is action. An action servlet is the primary component of the controller. In Struts 1. depending on which one is available. multiple submit buttons with the same name. the Struts v1. The button name is specified by the parameterproperty of the corresponding ActionMapping.

The purpose of Action Class is to translate the HttpServletRequest to the business logic. Struts is robust architecture and can be used for the development of application of any size. It knows nothing about the view or controller.  View: The view provides the presentation of the model. based on MVC-2 architecture.ActionServlet<servlet-class> <init-param> <param-name>application<param-name> <param-value>resource. we need to Subclass and overwrite the execute() method.Message resource definition files can available to the struts environment in two ways 1.apache. View and Controller:  Model: Components like business logic /business processes and data are the part of model. More about Model-View-Controller Architecture >> 2. The view should be notified when changes to the model occur. using web.What are the components of Struts? Struts components can be categorize into Model. . The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. 3. It is the look of the application. MVC decouples interface from business logic and data.xml as <servlet> <servlet-name>action<servlet-name> servlet-class>org. The view can access the model getters. The model encapsulates the state of the application. In the Action Class all the database/business processing are done. In addition. Struts framework makes it much easier to design scalable.What is Struts framework? Struts framework is an open-source framework for developing the web applications in Java EE. 1.  Model : The model contains the core of the application's functionality.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.struts. Sometimes the only functionality it contains is state. It creates and sets the model. but it has no knowledge of the setters. reliable Web applications with Java. 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. <message-resource key="myResorce" parameter="resource. 4. It uses and extends the Java Servlet API.  Controller:The controller reacts to the user input.action.What is a framework? A framework is made up of the set of classes which allow us to use a library in a best possible way for a specific requirement. It is advisable to perform all the database related stuffs in the Action Class.What is MVC? Model-View-Controller (MVC) is a design pattern put together to help control change. it knows nothing about the controller. To use the Action.Application<param-value> </servlet> 2.

It is the main Controller component that handles client requests and determines which Action will process each received request. Following is the method signature for thevalidate() method.  View: HTML. 5.xml file .  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. pages reference view roots via the JSF component tree. Struts framework creates ActionMapping object from <ActionMapping> configuration element of struts-config.What is ActionServlet? ActionServlet is a simple servlet which is the backbone of all Struts applications. 6. and JSP tags that make up a reusable MVC 2 design.How is the Action Mapping specified ? We can specify the action mapping in the configuration file called struts-config. servlets. 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.  Pages that represent MVC-style views. JSP are the view components. This class is to determine where the results of the Action will be sent once its processing is complete. 9.  JavaBeans components for managing application state and behavior.What are the core classes of the Struts Framework? Struts is a set of cooperating classes.HttpServletRequest request) reset(): reset() method is called by Struts Framework with each request that uses the defined ActionForm.xml.  Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests. public ActionErrors validate(ActionMapping mapping. 12. It serves as an Action factory – creating specific Action classes based on user’s request. Returns a collection of ActionError as ActionErrors. Called before FormBean is handed to Action.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.Describe validate() and reset() methods ? validate() : Used to validate properties after they have been populated.What are the important methods of ActionForm? The important methods of ActionForm are : validate() & reset().  Event-driven development (via listeners as in traditional GUI development). 10.What is the ActionForm? ActionForm is javabean which represents the form inputs containing the request parameters from the View referencing the Action bean.What is ActionMapping? Action mapping contains all the deployment information for a particular Action bean. 7.

jsp"/> <forward name="failure" path="/error.xml file for a single Struts application? Yes. HttpServletResponse response) throws Exception .xml for a single Struts application. Struts controller uses the command design pattern and the action classes use the adapter design pattern.<action-mappings> <action path="/submit" type="submit. we can have more than one struts-config. ActionForm form. execute() method of Action class:  Perform the processing required to deal with this request  Update the server-side objects (Scope variables) that will be used to create the next page of the user interface  Return an appropriate ActionForward object 15.apache.action. 14. The process()method of the RequestProcessor uses the template method design pattern.ActionServlet . public ActionForward execute( ActionMapping mapping.jsp" scope="request" validate="true"> <forward name="success" path="/success.In which method of Action class the business logic is executed ? In the execute() method of Action class the business logic is executed. Struts also implement the following J2EE design patterns.Can we have more than one struts-config.jsp"/> </action> </action-mappings> 13.What design patterns are used in Struts? Struts is based on model 2 MVC (Model-View-Controller) architecture. HttpServletRequest request.struts.  Service to Worker  Dispatcher View  Composite View (Struts Tiles)  Front Controller  View Helper  Synchronizer Token 16. They can be configured as follows: <servlet> <servlet-name>action</servlet-name> <servlet-class> org.What is role of Action Class? An Action Class performs a role of an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request.SubmitAction" name="submitForm" input="/submit.

What is the directory structure of Struts application? The directory structure of Struts application : 18.What is the difference between session scope and request scope when saving formbean ? when the scope is request. /WEB-INF/struts-admin.xml ? The five important sections are: . when the scope is session.the values of formbean would be available for the current request.xml </param-value> </init-param> .the values of formbean would be available throughout the session.xml.What are the important tags of struts-config... <servlet> 17. /WEB-INF/struts-config-forms. </servlet-class> <init-param> <param-name>config</param-name> <param-value> /WEB-INF/struts-config...xml. 19.

What are the different kinds of actions in Struts? The different kinds of actions in Struts are:  ForwardAction  IncludeAction  DispatchAction  LookupDispatchAction  SwitchAction 21. 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. It picks a method to invoke based on an incoming request parameter. 22.  Add an entry to struts-config.  Do not override execute() method – Because DispatchAction class itself provides execute() method.20. The DispatchAction dispatches to one of the logical actions represented by the methods. Using this class.xml .What is DispatchAction? The DispatchAction class is used to group related actions into one class. follow these steps :  Create a class that extends DispatchAction (instead of Action)  In a new class. you can have a method for each logical action compared than a single execute method.How to use DispatchAction? To use the DispatchAction. The value of the incoming parameter is the name of the method that the DispatchAction will invoke.

What is LookupDispatchAction? The LookupDispatchAction is a subclass of DispatchAction. 25. without extending.DispatchAction Example » 23. 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. Use ForwardAction to forward a request to another resource in your application. you don’t have to write your own Action class.What is the use of ForwardAction? The ForwardAction class is useful when you’re trying to integrate Struts into an existing application that uses Servlets to perform business logic functions. You just have to set up thestruts-config file properly to use ForwardAction. Since the key is always the same. 30.What are the steps need to use DynaActionForm? Using a DynaActionForm instead of a custom subclass of ActionForm is relatively straightforward. such as a Servlet that already does business logic processing or even another JSP page.struts.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.apache. 32. without having to rewrite the existing Servlets. Instead the <action> element’s<forward> takes precendence.xml: change your <form-bean> to be anorg. 31. Use ForwardAction to forward a request to another resource in your application. 26. 29. You can use this class to take advantage of the Struts controller and its functionality. 27. 28. Use the IncludeAction class to include another resource in the response to the request being processed. By using this predefined action. The SwitchAction class can be used as is.action.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.What if <action> element has <forward> declaration with same name as global forward? In this case the global forward is not used. the LookupDispatchAction shields your application from the side effects of I18N. without requiring the developer to create a Java class for each type of form bean.What is IncludeAction? The IncludeAction class is useful when you want to integrate Struts into an application that uses Servlets. 24. SwitchAction is useful only if you have multiple modules in your Struts application.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.DynaActionForm instead of some subclass of ActionForm .What is SwitchAction? The SwitchAction class provides a means to switch from a resource in one module to another resource in a different module.What is DynaActionForm? A specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of properties (configured in configuration file). such as a Servlet that already does business logic processing or even another JSP page. You need to make changes in two places:  In struts-config. but by the Locale independent key into the resource bundle.

http.. new ActionMessage( "error.apache. if (((String) loginForm.<form-bean name="loginForm"type="org.apache. import org.required")).ActionForward.action.Action.action.What is the use of <logic:iterate>? . } ..equals("")) { errors.get("userName")).. 33.required")).action.struts.apache.struts.apache.apache. ActionMessages errors = new ActionMessages().. import org...ActionMapping.. 34.HttpServletRequest.struts. import javax. import org.action.equals("")) { errors.. ActionForm form.ActionMessages. import org. import org.struts.action.get("password")). import org.DynaActionForm" > <form-property name="userName" type="java.servlet. public class DynaActionFormExample extends Action { public ActionForward execute(ActionMapping mapping.servlet.action.apache.userName.How to display validation errors on jsp page? <html:errors/> tag displays all the errors.action.struts.struts. HttpServletRequest request.ActionForm.action.String"/> <form-property name="password" type="java.DynaActionForm o downcast the ActionForm parameter in execute() to a DynaActionForm o access the form fields with get(field) rather than getField() import javax.apache..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.struts.add("password". } if (((String) loginForm. import org..lang.apache.String" /> </form-bean>  In your Action subclass that uses your form bean: o import org.DynaActionForm.lang. HttpServletResponse response) throws Exception { DynaActionForm loginForm = (DynaActionForm) form.apache.password.HttpServletResponse.struts. <html:errors/> iterates over ActionErrors request attribute.ActionMessage.struts.add("userName".http. new ActionMessage( "error.action.

. <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.key" type="java. <bean:write> has no body.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. This approach applies only to exceptions thrown by Actions. Whereas. It works well when custom page needed when error occurs. of variable) needed when error occurs. usingDynaActionForm there is no need of providing properties to hold the state..e. Detecting them at runtime is painful and makes you go through redeployment.  The DynaActionForm is not strongly typed as the ActionForm.jsp"/> 38.NullPointerException" path="/WEB-INF/errors/null.firstname"/> <bean:write>: is used to retrieve and print the value of the bean property. <bean:message key="prompt. Instead these properties and their type are declared in the struts-config.jsp"/> </global-exceptions> or <exception key="some.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. <bean:write name="customer" property="firstName"/> 37.customer. <global-exceptions> <exception key="some.key" type="package. This means there is no compile time checking for the form fields.  ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.  Declarative exception handling :You can either define <global-exceptions> handling tags in yourstruts- config. It also supports the ability to include parameters that can be substituted for defined placeholders in the retrieved string.xml  The DynaActionForm bloats up the Struts config file with the xml based definition.lang.SomeException" path="/WEB-INF/somepage. This gets annoying as the Struts Config file grow larger.<logic:iterate> repeats the nested body content of this tag over a specified collection.What are differences between <bean:message> and <bean:write> <bean:message>: is used to retrive keyed values from resource bundle. It works well when custom value (i.xml or define the exception handling tags within <action></action> tag.

Struts is robust architecture and can be used for the development of application of any size. It is the look of the application.struts. as well as Velocity Templates. It knows nothing about the view or controller. <message-resources parameter="com.. like Hibernate. .  ActionForm were designed to act as a Firewall between HTTP and the Action classes. Q 2. isolate and encapsulate the HTTP request parameters from direct use in Actions. What is Struts framework? Struts framework is an open-source framework for developing the web applications in Java EE.login. ).getParameter( . Sometimes the only functionality it contains is state. including JSTL and JSF. The view can access the model getters. With DynaActionForm. like JDBC and EJB. and other presentation systems. it knows nothing about the controller. XSLT. In addition.xml. Q 3.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.  DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be avoided. 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. The model enca psulates the state of the application. View: The view provides the presentation of the model. Model: The model contains the core of the application's functionality. the property access is no different than using request. What is MVC? Model-View-Controller (MVC) is a design pattern put together to help control change. The view should be notified when changes to the model occur. Struts provides its own Controller component and integrates with other technologies to provide the Model and the View. MVC decouples interface from business logic and data. or Object Relational Bridge. It uses and extends the Java Servlet API. iBATIS.e. as well as most any third-party packages. reliable Web applications with Java. Struts can interact with standard data access technologies.ApplicationResources"/> 40. It creates and sets the model. For the View. For the Model. but it has no knowledge of the setters. Struts framework makes it much easier to design scalable.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. Controller: The controller reacts to the user input. based on MVC-2 architecture. Struts works well with JavaServer Pages. i. o 39.

findForward("success"). public class TestAction extends Action { public ActionForward execute(ActionMapping mapping.Action is called Action class.action.action. we need to Subclass and overwrite the execute() method. Q 5. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class. 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.  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 Q 7. An ActionForm is also called JavaBean.struts. Q 6.. Jakarta Struts is robust architecture and can be used for the development of application of any size. the business objects could be handed to the action at runtime (IoC style) thus removing any dependencies on the model.apache. call business objects (which then handle database. The action should receive the request.action. reliable Web applications with Java. 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.servlet.*. Controller is responsible for handling all the requests. What is Action Class? Any java class which extends from org.durgasoft. What is ActionForm? Any java class which extends from org. All the requests to the server goes through the controller.struts. In the the Jakarta Struts Framework this class plays the role of controller. ActionForm form. Struts framework makes it much easier to design scalable. etc) and then determine where to go next. HttpServletRequest request. Q 8. What is ActionServlet? The class org. The purpose of Action Class is to translate the HttpServletRequest to the business logic. It can be use to validate the data on the users browser as well as on the server side. Q10. import org.struts.ActionForm is called ActionForm. There should be no database interactions in the action. The Action is part of the controller.HttpServletResponse response) throws Exception { return mapping. } } Q 9.apache. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. What is Jakarta Struts Framework? Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications.action. Even better. What is Struts Validator Framework? Struts Framework provides the functionality to validate the form data.*. . Write code of any Action Class? package com. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. import javax.apache. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.apache.ActionServlet is the called the ActionServlet.Q 4.struts. To use the Action.http. or interface with J2EE.

ActionMapping class.do The preceding mapping is called extension mapping. invoke a business operation and coordinating the view to return to the client.do are mapped to this servlet in the deployment descriptor as follows. Each Action element is represented in memory by an instance of the org. http://localhost:8080/mycontext/do/action_Name The class org. It acts as a bridge between a client-side user action and business operation. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings. <servlet> <servlet-name>action</servlet-name> <servlet-class>org.http. All incoming requests are mapped to the central controller in the deployment descriptor as follows.requestProcessor process the request from the controller. You can sublass the RequestProcessor with your own version and modify how the request is processed. The ActionServlet class is not abstract and therefore can be used as a concrete controller by your application. Action are mapped in the struts configuration file and this configuration is loaded into memory at startup and made available to the framework at runtime. you can also specify path mapping where a pattern ends with /* as shown below.apache. The Action class decouples the client request from the business model. The Action class also can perform other functions such as authorization.struts. This decoupling allows for more than one-to-one mapping between the user request and an action. What is RequestProcessor? The controller is responsible for intercepting and translating user input into actions to be performed by the model. it delegates the handling of the request to a helper class.apache. This helper knows how to execute the business operation associated with the requested action. The controller is implemented by the ActionServlet class. The Controller receives the request from the browser.ActionServlet</servlet-class> </servlet> All request URIs with the pattern *. logging before invoking business operation.do</url-pattern> <servlet-mapping> A request URI that matches this pattern will have the following form.struts.Action class.httpServlet class. The controller is responsible for selecting the next view based on user input and the outcome of model operations. public ActionForward execute(ActionMapping mapping. The ActionMapping object contains a path attribute that is matched against a portion of the URI of the incoming request.action. the Struts Action class contains several methods. this servlet is centralized point of control for the web application. however. ActionForm form.struts.The controller is implemented by a java servlet.action. <action> path= "/somerequest" . <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>/do/*</url-pattern> <url-pattern>*. HttpServletResponse response) throws Exception The execute() method is called by the controller when a request is received from a client.apache. HttpServletRequest request. <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*. Q11. The controller creates an instance of the Action class if one doesn?t already exist.action.servlet.The Validator framework was developed by David Winterfeldt as third-party add-on to Struts.action. How you will display validation fail errors on jsp page? Following tag displays all the errors: <html:errors/> Q12. but most important method is the execute() method. In struts framework the controller responsibilities are implemented by several different components like The ActionServlet Class The RequestProcessor Class The Action Class The ActionServlet extends the javax.apache. Once the controller receives a client request. http://localhost:8080/mycontext/actionName. The strut framework will create only a single instance of each Action class in your application. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts.struts. In the Struts framework this helper class is descended of org.do</url-pattern> A request URI that matches this pattern will have the following form.

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. LookupDispatchAction. type="com.jsp" redirect="true"/> </action> The action forward mappings also can be specified in a global section. What are the different kinds of actions in Struts? The different kinds of actions in Struts are: ForwardAction. Example: <exception key="database. How to use DispatchAction? To use the DispatchAction.jsp" <forward name="Success" path="/action/xys" redirect="true"/> <forward name="Failure" path="/somejsp. What is DispatchAction? The DispatchAction class is used to group related actions into one class. Q16.DuplicateUserException"/> b) Programmatic Exception Handling: Here you can use try{}catch{} block to handle the exception.jsp" /> </global-forwards> Q13. <global-forwards> <forward name="Success" path="/action/somejsp.ActionForward class.error.apache. The execute method signature in Action class has a return type org. Q14.</action> tag. It picks a method to invoke based on an incoming request parameter. you can have a method for each logical action compared than a single execute method. Using this class. you can declaratively associate as action forward through out the application.somepackage. The action forward are specified in the configuration file.account. DispatchAction.jsp" /> <forward name="Failure" path="/someotherjsp.duplicate" path="/UserExists.action. The DispatchAction dispatches to one of the logical actions represented by the methods. The value of the incoming parameter is the name of the method that the DispatchAction will invoke.jsp" redirect="true"/> </action> Once this is done the controller should determine which view to return to the client.jsp" <forward name="Success" path="/action/xys" redirect="true"/> <forward name="Failure" path="/somejsp.jsp" type="mybank.somepackage.. follow these steps : 1. struts. Create a class that extends DispatchAction (instead of Action) . SwitchAction Q15. IncludeAction. independent of any specific action mapping.xml or define the exception handling tags within <action>. <action> path= "/somerequest" type="com.someAction" scope="request" name="someForm" validate="true" input="somejsp.someAction" scope="request" name="someForm" validate="true" input="somejsp. 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 will provide properties to hold the state of the form with getters and setters to access them. ActionForm were designed to act as a Firewall between HTTP and the Action classes. The DynaActionForm bloats up the Struts config file with the xml based definition. What is difference between ActionForm and DynaActionForm? An ActionForm represents an HTML form that the user interacts with over one or more pages. isolate and encapsulate the HTTP request parameters from direct use in Actions. Q18. 2. What is LookupDispatchAction? The LookupDispatchAction is a subclass of DispatchAction. Q21. ). 4. 3.xml Q17.xml. but by the Locale independent key into the resource bundle. SwitchAction is useful only if you have multiple modules in your Struts application. i. What is SwitchAction? The SwitchAction class provides a means to switch from a resource in one module to another resource in a different module.  DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be avoided.What are the important tags of struts-config. With DynaActionForm.xml ? .get Parameter( . the property access is no different than using request. the LookupDispatchAction shields your application from the side effects of I18N. Instead the <action> element’s <forward> takes precendence. Instead these properties and their type are declared in the struts-config. In a new class. 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. 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. 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 Q24. 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. 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. The SwitchAction class can be used as is.e. This means there is no compile time checking for the form fields. Whereas. The DynaActionForm is not strongly typed as the ActionForm. using DynaActionForm there is no need of providing properties to hold the state.. Q20. Q23. This gets annoying as the Struts Config file grow larger. Do not override execute() method – Because DispatchAction class itself provides execute() method. What if <action> element has <forward> declaration with same name as global forward? In this case the global forward is not used. without extending. Since the key is always the same. Q19. Q22. ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file. Add an entry to struts-config. Detecting them at runtime is painful and makes you go through redeployment.

========== Form Bean Definitions ============ --> <form-beans> <form-bean name="login" type=" LoginForm" /> </form-beans> <!-. public void reset() {} Q28. How you will enable front-end validation based on the xml in validation.xml"/> </plug-in> </struts-config> Q25.struts.xml and validation. The validation. As we already mentioned. Following is the method signature for the validate() method.xmldefines the standard validation routines. In Struts 1. The purpose of this method is to reset all of the ActionForm's data members prior to the new request values being set. The validator- rules.xml defines the validations applied to a form bean. associates an action name with an action.1 ActionServlet is smart enough to know whether or not it should call perform or execute . HttpServletRequest request) reset(): reset() method is called by Struts Framework with each request that uses the defined ActionForm. The <html:javascript> when added in the jsp file generates the client site validation script. Q30. Action.perform() is now deprecated. Q27.xml. Action.1. public ActionErrors validate(ActionMapping mapping. the Struts v1. Now execute just throws Exception.xml.xml. or at least the flow control to your JavaBeans and EJBs that handle your business logic.========== Action Mapping Definitions ======== --> <action-mappings> <action path="/login" type="LoginAction" > </action> </action-mappings> <!-.perform() is the method called by the ActionServlet. Returns a collection of ActionMessage as ActionErrors.x.apache. Action Forward.validator. to support declarative exception handling. 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. to define the form specific validations. What is the difference between perform() and execute() methods? perform() method defined in Struts 1.xml file. Action. however.ValidatorPlugIn"> <set-property property="pathnames" value="/org/apache/struts/validator/validator-rules. /WEB-INF/validation. Give the Details of XML files used in Validator Framework? The Validator Framework uses two XML configuration files validator-rules.xml? The <html:javascript> tag to allow front-end validation based on the xml in validation. This is typically where your business logic resides. the method signature changed in perform.========== Properties Definitions ============ --> <message-resources parameter="MessageResources" /> <!-. An action mapping can contain a reference to a form bean that the action can use. in general. ActionMapping. What are the core classes of the Struts Framework? A: Core classes of Struts Framework are ActionForm. ActionServlet etc. Q29. Describe validate() and reset() methods ? validate () and reset() methods defined inActionForm class. What is action mappings? An action mapping is a configuration file entry that. but it is was deprecated in the Struts Version 1.0.========== Global Forward Definitions ========= --> <global-forwards> </global-forwards> <!-.<struts-config> <!-. these are reusable and used in validation.xml. Q26. Called before FormBean is handed to Action. and can additionally define a list of local forwards that is visible only to this action. validate() : Used to validate properties after they have been populated.========== Validator framework Definitions ============ --> <plug-in className="org.

What are the steps need to use DynaActionForm? Using a DynaActionForm instead of a custom subclass of ActionForm is relatively straightforward. radio buttons etc. without having to rewrite the existing Servlets.apache.For the application using tiles * Nested tag library .apache.String"/> <form-property name="password" type="java.lang. You just have to set up the struts-config file properly to use ForwardAction. Q36. text boxes. iteration capabilities and flow management * Tiles or Template tag library .action. Q35. * Logic tag library .37 In struts what happens if made any changes in actionservlet? The ActionServlet plays the role of controller wich is responsible for handling the request and selecting the correct Application Module and storing ApplicationConfig and MessageResource bundle in the request object. you don’t have to write your own Action class.xml: change your <form-bean> to be an org. Use the IncludeAction class to include another resource in the response to the request being processed. checkboxes.action. Q34. <bean:write>: This tag is used to output property values from a bean.action. What is the use of ForwardAction? The ForwardAction class is useful when you’re trying to integrate Struts into an existing application that uses Servlets to perform business logic functions. These tag libraries are: * Bean tag library . Q33. If we modify the ActionServlet the Controller may or may not work what happens that depends on your modification. .apache.lang. <bean:write> is a commonly used tag which enables the programmers to easily present the data.Tags for generating conditional output. and up to four placeholder arguments used for parametric substitution in the resulting message. Each individual message is described by an ActionMessage object. * HTML tag library . By using this predefined action. 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. therefore.struts. Validation errors are either global to the entire ActionForm bean they are associated with. You need to make changes in two places: In struts-config.. 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.Tags for accessing JavaBeans and their properties. You can use this class to take advantage of the Struts controller and its functionality. which contains a message key (to be looked up in an appropriate message resources database). such as a Servlet that already does business logic processing or even another JSP page. or they are specific to a particular bean property (and. a particular input field on the corresponding form). including forms. Messages can be either global or they are specific to a particular bean property.String" /> </form-bean>  In your Action subclass that uses your form bean: o import org. You have not specify whether you want to create your own custom ActionServlet by extending ActionServlet and overriding the methods in it or what exactly you want to modify.For using the nested beans in the application Q32.DynaActionForm" > <form-property name="userName" type="java.struts. Struts provide many tag libraries to ease the development of web applications.in the Action. depending on which one is available.Tags to output standard HTML. Use ForwardAction to forward a request to another resource in your application. Q31. ActionErrors: A class that encapsulates the error messages being reported by the validate() method of an ActionForm.struts. What are difference between ActionErrors and ActionMessage? ActionMessage: A class that encapsulates messages.Dyna ActionForm instead of some subclass of ActionForm  <form-bean name="loginForm"  type="org. What is IncludeAction? The IncludeAction class is useful when you want to integrate Struts into an application that uses Servlets.DynaActionForm o downcast the ActionForm parameter in execute() to a DynaActionForm o access the form fields with get(field) rather than getField() Q.