What is Struts and
how it helps in web development?
Apache Struts is a free open-source
framework for creating Java web applications. Struts helps in providing
dynamism to a web based application in contrast with many websites that deliver
only static pages. A web application interacts with databases and business
logic engines to customize a response.
Struts is based on MVC(Model-View-Controller) architecture based and it clearly
segregate business logic from presentation which is somehow difficult to
achieve with JavaServer Pages that sometimes mingle database code, page design
code, and control flow code. Unless these components are not separated then it
becomes quite difficult to maintain in large web based applications. The Model
represents the business or database code, the View represents the page design
code, and the Controller represents the business logic or navigational code.
You should always wear formal dresses for an interview - please check Why you should wear formal for an interview
Formal dresses for men
Formal dresses for women
The framework
provides three key components:
- A "request" handler
provided by the application developer. It maps to a standard URI.
- A "response" handler
that transfers control to another resource which completes the response.
- A tag library that helps
developers create interactive form-based applications with server pages.
Struts works well with conventional REST applications and
with new technologies like SOAP and AJAX.
By the time posting of this article, the latest version of Apache Struts is
'Struts 2.0.6', according to Apache it is an elegant, extensible framework for
creating enterprise-ready Java web applications, was originally known as
WebWork 2.
Explain Struts1.x in a
nutshell?
Struts are consisted of technologies like Java Servlets,
JavaBeans, ResourceBundles, and XML, as well as various Jakarta Commons
packages, like BeanUtils and Chain of Responsibility. It helps one create an
extensible development environment for one's application, based on published
standards and proven design patterns.
Whenever a request comes from web browser then application's controller handles
this request. When request is received then Controller invokes an Action class.
This Action class object then communicates with Model class (which actually is
a set of JavaBeans representation) to examine or update the application's
state. The Struts ActionForm class helps in data exchange between Model and
View layers.
A web application uses 'web.xml', a deployment descriptor to initialize
resources like servlets and taglibs. Similarly, Struts uses a configuration
file( struts-config.xml) to initialize its own resources. These resources
include ActionForms to collect input from users, ActionMappings to direct input
to server-side Actions, and ActionForwards to select output pages. Moreover, one
can specify validations for the ActionForms in an XML descriptor, using the
Struts Validator. A standard extension, Tiles, helps you build pages from
smaller fragments...
Struts may not be a useful option for each type of web development application.
If the application is huge and complex then Struts fits the bill in best way
but if you are developing a web application which requires very little of web
pages and business logic then MVC-1 based approach will be best rather MVC-2
based like Struts.
Give an overview of Struts? SF DP
A 110: Struts
is a framework with set of cooperating classes, servlets and JSP tags that make
up a reusable MVC 2
design.
S TR U TS O v e r v iew
C lie n t
(BR O W SER )
V ie w
(JS P )
A ctio n
(c a lls b u s in e s s lo g ic )
M o d e l
(F o rm b e a n s )
1 . H T TP reque st
2 . D i sp a tc h
3. Instantiate/ Set
5 . g e t th ro u g h Ta g
6 . H TT P r e spo nse
4. Foprward
F ro n t
C o n tro l le r
(S e rvle t )
s tr u ts -
c o n f ig .xm l
􀂃 Client (Browser): A request from the client browser creates an HTTP request. The Web
container will
respond to the request with an HTTP response, which gets displayed on
the browser.
Enterprise Java
134
􀂃 Controller (ActionServlet class and Request Processor class): The controller receives the request from
the browser, and makes the decision where to send the request based on
the struts-config.xml. Design
pattern: Struts
controller uses the command
design pattern by calling the Action classes based on the
configuration file struts-config.xml and the RequestProcessor
class’s process() method uses template
method design pattern (Refer Q11 in How would you go about … section) by calling a sequence of methods
like:
• processPath(request, response) ô€ƒ† read
the request URI to determine path element.
• processMapping(request,response) ô€ƒ† use
the path information to get the action mapping
• processRoles(request,respose,mapping) ô€ƒ† Struts Web application security which
provides an
authorization scheme. By default calls request.isUserInRole(). For
example allow /addCustomer action if
the role is executive.
<action path=”/addCustomer” roles=”executive”>
• processValidate(request,response,form,mapping) ô€ƒ† calls the vaildate() method of the
ActionForm.
• processActionCreate(request,response,mapping)ô€ƒ† gets the name of the action class from the
“type”
attribute of the <action> element.
• processActionPerform(req,res,action,form,mapping) ô€ƒ† This method calls the execute method of the
Action class which is where business logic is written.
􀂃 Business Logic (Action class): The Servlet dispatches the request to Action classes, which act as a thin
wrapper to the business logic (The actual business logic is carried out by either EJB session beans
and/or
plain Java classes). The action class helps control the workflow of
the application. (Note: The Action class
should only control the workflow and not the business logic of the
application). The Action class uses the
Adapter design pattern (Refer Q11 in How would you go about … section).
􀂃 ActionForm class: Java representation of HTTP input data. They can carry data over from
one request to
another, but actually represent the data submitted with the request.
􀂃 View (JSP): The
view is a JSP file. There is no business or flow logic and no state
information. The JSP
should just have tags to represent the data on the browser.
ActionServlet class
is the controller part of the MVC implementation and is the core of the
framework. It
processes user requests, determines what the user is trying to achieve
according to the request, pulls data from
the model (if necessary) to be given to the appropriate view, and
selects the proper view to respond to the user.
As discussed above ActionServlet class delegates the grunt of the work
to the RequestProcessor and Action
classes.
The ActionForm class
maintains the state for the Web application. ActionForm is an abstract class,
which is
subclassed for every input form model. The struts-config.xml file
controls, which HTML form request maps to
which ActionForm.
The Action class
is a wrapper around the business logic. The purpose of the Action class is to
translate the
HttpServletRequest to the business logic. To use the Action class,
subclass and overwrite the execute() method.
The actual business logic should be in a separate package or EJB to
allow reuse of business logic in protocol
independent manner (ie the business logic should be used not only by
HTTP clients but also by WAP clients,
EJB clients, Applet clients etc).
The ExceptionHandler can be defined to execute when the Action class’s execute() method
throws an Exception.
For example
<global-exceptions>
<exception key="my.key"
type="java.io.IOException"
handler="my.ExceptionHandler"/>
</global-exceptions>
When an IOException is thrown then it will be handled by the execute()
method of the my.ExceptionHandler class.
The struts-config.xml configuration information is translated into ActionMapping,
which are put into the
ActionMappings collection.
Further reading is recommended for more
detailed understanding.
What are the methods in Action
class?
An Action class in the struts
application extends Struts 'org.apache.struts.action.Action" class. Action
class acts as wrapper around the business logic and provides an interface to
the application's Model layer. Action class mediates between the View and Model
layer in both directions it means it transfers data to and fro from the view
layer and the specific business process layer.
If you look at the sequence diagram, it gives you a correct picture how an
Action class instance is invoked. When it is invoked then overridden execute()
method is invoked. It is advisable not to put the business process logic inside
execute method which should ideally have navigational logic details, instead
move the database and business process logic to DAO layer.
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, mapping of
which is provided in struts-config.xml file.
package dpun.action;
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;
public class MyAction extends Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm actionForm,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
return
mapping.findForward("myAction");
}
}
Action class has
two execute methods, one HTTP specific and the other protocol independent. The
HTTP based execute method has following parameters:
ActionMapping mapping: This object is
used to refer this instance.
ActionForm actionForm: It refers
ActionForm bean class associated with this request. HttpServletRequest request: It represents HTTP request.
HttpServletResponse response: It
represents HTTP response.
While protocol independent execute has ServletRequest and ServletResponse
instead of HttpServletRequest and HttpServletResponse parameters
How you will handle errors and
exceptions in Struts?
An
efficient error and exception handling makes an application behave gracefully
under abnormal conditions. Struts has errors and exception handling done in
different ways. The form validations using Struts require a proper mechanism. For
handling errors in Struts, it has two objects ActionError and ActionErrors. Whenever
a form is submitted then cotroller receives request and then create ActionForm
object which calls reset() method and stores ActionForm object to required
scope and then it loads ActionForm object from request and calls validate()
method. If validate method fails then errors are displayed on the form itself
through <html:errors> tags.
Exception Handling can be done in following ways:
-try-catch block
within
-Using
declarative exception handling. In struts-config.xml we can declare on which
type of exception, a request should be redirected to.
Use Global
Exceptions tag in struts-config.xml
<global-exceptions>
<exception
key="errors.MyException"
type="java.lang.MyException" path="/myExcption.jsp"/>
So
whenever MyException occurs then Struts framework will display
'myException.jsp' page.
The
interpretation of this is that if MyException is caught by Struts'
ActionServlet then it should redirect to myExcption.jsp. The key is as usual a
pointer to the message resource file.
How does Validator framework
work in Struts ?
The Validator framework is an open source project and is
part of the Jakarta Commons subproject. The Commons project was created for the
purpose of providing reusable components like the Validator. Other well-known
Commons components include BeanUtils, Digester, and the Logging framework. It
was first released in November 2002.
Validator framework consists of the following components:-
-Validators
-Configuration Files
-Resource Bundle
-JSP Custom Tags
-Validator Form Classes
Validators
are Java classes which execute validation rule. The framework knows how to
invoke a Validator class based on its method signature, as defined in a
configuration file. Typically, each Validator provides a single validation
rule, and these rules can be chained together to form a more complex set of
rules.
Configuration Files: There are two configuration files
-validator.xml and
-validator-rules.xml
validator-rules.xml contains all possible validations available to an
application. These validations are present as definitions in this file. The
controlling document of Validator-rules.xml is Validator-rules_1_1.dtd.All the
elements defined in this file are defined according to the above DTD.
The required validation is applied to mandatory fields, such as employee id(one
example).The has many attributes. These attributes
are,Name,Classname,MethodMethodparams,Msg
A simple validator-rule.xml file.click here.
Another configuration file is validation.xml file. It is where you
couple the individual Validators defined in the validator-rules.xml to components
within your application. Since we are talking about using the Validator with
Struts, the coupling occurs between the Validators and Struts ActionForm
classes.ActionForm also provide a convenient spot to validate the user input
before passing it to the business layer. Here is a simple validation.xml
file.
Resource Bundle: Resource Bundle forms the base of localization. The error
messages created when a rule fails come from the resource bundles. For the
common Validators provided by the Validator framework, the default messages can
be placed in the Struts application's message resources. Some of these messages
are:
#Error messages used by the Validatorerrors.required={0} is required.errors.minlength={0} can not be less than {1} characters.errors.maxlength={0} can not be greater than {1} characters.errors.invalid={0} is invalid.
The parameter in place of {0} and {1}
is inserted automatically by the framework when the rules fail. These values
are corresponding to the parameters comes from the Validator-rules.xml and
validation.xml files.
JSP
Custom Tags
Like errors and javascript
Struts HTML tags required in case of validations. The former is for server-side
validation while the latter is for client side validation.
Validator
Form Class
In Struts data is passed from the JSP
page (view layer) to Action class (controller layer) by means of ActionForm
objects. The standard Struts ActionForm won't suffice to impose validation framework.The
specially designed classes for this purpose come quite handy. It comes in two
varieties- ValidatorForm and DynaValidatorForm. The former is used in place of
ActionForm while the latter is used with the DynaActionForm. Whatever the
variety being used, two methods used for performing validation which are
present in both of them are- reset() and validate().
Integrating validator to Struts is done by introducing the following piece of data
inside strust-config.xml:
The Validator framework is easily extensible and the effort required is
minimal.
-Create your own validation classes.
-Hook it up inside validation-rules.xml file
Apart from using in Struts application,the Validator framework can be used as a
separate unit for validation of applications.
What is Struts Validator Framework?
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
Framework emits the java scripts and it
can be used validate the form data on the
client browser. Server side validation
of form can be accomplished by sub classing
your From Bean with DynaValidatorForm
class.
The Validator framework was developed by
David Winterfeldt as third-party
add-on to Struts. Now the Validator
framework is a part of Jakarta Commons project
and it can be used with or without
Struts. The Validator framework comes integrated
with the Struts Framework and can be
used without doing any extra settings.
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
validator-rules.xml defines 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.
How you will display validation fail
errors on jsp page?
Following tag displays all the errors:
<html:errors/>
How you will enable front-end validation
based on the xml in
validation.xml?
Struts Interview Questions
http://marancollects.blogspot.com 3/5
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.
How does Validator framework
work in Struts ?
org.apache.struts.actions.DispatchAction is responsible for
-Dispatches to a public method named on a request parameter
-Method name corresponds to the 'parameter' property of corresponding
ActionMapping
-useful when multiple similar actions are to be clubbed within a single Action
class in order to simplify the design.
If you want to insert, update and delete all actions on a database from a JSP
with the same Action class in such case it will come quite handy.
Here is how this JSP looks like:
<html:form action="/saveSubscription">
<html:submit>
<bean:message key="insert"/>
</html:submit>
<html:submit>
<bean:message key="update"/>
</html:submit>
<html:submit>
<bean:message key="delete"/>
</html:submit>
</html:form>
To configure the use of this action in your struts-config.xml file, create an
entry like this:
<action path="/saveSubscription"
type="org.apache.struts.actions.DispatchAction" name="subscriptionForm"
scope="request" input="/subscription.jsp"
parameter="submit"/>
It will use the value of the request parameter named "submit" to pick
the appropriate "execute" method, which must have the same signature
(other than method name) of the standard Action.execute method. For example,
you might have the following three methods in the same action:
* public ActionForward delete(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
* public ActionForward insert(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
* public ActionForward update(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
In our JSP, we can refer to the buttons in the usual way. Later, when the user
selects a button, the form will pass the submit parameter, along with whatever
message is Struts finds for "insert" or "delete" in the
resource bundle.
Using the conventional DispatchAction, this approach would be problematic, not
necessarily each message will map to a valid Java identifier. This is where the
magic of the LookupDispatchAction comes into play.
When you create your LookupDispatchAction subclass, along with the methods for
the dispatch operations you must also implement a getKeyMethodMap method. This
is a "hotspot" that the LookupDispatchAction will call.
Here's an example of the methods you might declare in your subclass:
protected Map getKeyMethodMap(ActionMapping mapping,
ActionForm form,
HttpServletRequest request) {
Map map = new HashMap();
map.put("button.add", "add");
map.put("button.delete", "delete");
return map;
}
Internally, the base action will look up the messages for 'insert' and
'delete', and match those against the submit parameter. When it finds a match,
it will then use either "insert" or "delete" to call the
corresponding methods.
So while the LookupDispatchAction means adding an extra method to your Action,
it lets you skip putting a JavaScript in your form.
Both the DispatchAction and LookupDispatchAction are an excellent way to
streamline your Struts action classes, and group several related operations
into a single umbrella action. So, how many dispatch actions do you need? Can
you use a dispatch action to collect everything into a single action?
In practice, you can easily use one dispatch action for any forms that share a
common validation. It is not advisable to have sharing of dispatch action
between different form beans, or form beans that are validated differently, as
it can start to make things harder rather than simpler. But the use of a
dispatch action can easily half or quarter the number of action classes in most
Struts application.
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.
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.
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.
What are the components of
Struts?
Struts
components can be categorize into Model, View and Controller:
- Model: Components
like business logic /business processes and data are the part of model.
- View: HTML, JSP
are the view components.
- Controller: Action
Servlet of Struts is part of Controller components which works as front
controller to handle all the requests.
Struts components
- All the core components of Struts
framework belong to Controller category.
- Struts has no components in the Model
category.
- Struts has only auxiliary components in
View category. A collection of custom tags making it easy to interact with
the controller. The View category is neither the core of Struts framework
nor is it necessary. However it is a helpful library for using Struts effectively
in JSP based rendering.
Controller
Category: The ActionServlet and the collaborating
classes form the controller and is the core of the framework. The collaborating
classes are RequestProcessor, ActionForm, Action, ActionMapping and ActionForward.
View Category: The View category contains utility classes – variety of custom
tags making it easy to interact with the controller. It is not mandatory to use
these utility classes. You can replace it with classes of your own. However when
using Struts Framework with JSP, you will be reinventing the wheel by writing
custom tags that mimic Struts view components. If you are using Struts with
Cocoon or Velocity, then have to roll out your own classes for the View category.
Model Category: Struts does not offer any components in the Model Category.
You are on you own in this turf. This is probably how it should be. Many
component models (CORBA, EJB) are available to implement the business tier.
Your model components are as unique as your business and should not have any
dependency on a presentation framework like Struts. This philosophy of limiting
the framework to what is absolutely essential and helpful and nothing more has
prevented bloating and made the Struts framework generic and reusable.
NOTE: Some people argue that ActionForm is
the model component. However ActionForm is really part of the controller. The
Struts documentation also speaks along similar lines. It is just View Data
Transfer Object – a regular JavaBeans that has dependencies on the Struts classes
and used for transferring the data to various classes within the controller.
What are the core classes of
the Struts Framework?
Struts is a
set of cooperating classes, servlets, and JSP tags that make up a reusable MVC
2 design.
- JavaBeans components for managing
application state and behavior.
- Event-driven development (via
listeners as in traditional GUI development).
- Pages that represent MVC-style
views; pages reference view roots via the JSF component tree.
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 user’s request.
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
What is the ActionForm?
ActionForm is
javabean which represents the form inputs containing the request parameters
from the View referencing the Action bean.
What are the important methods
of ActionForm?
The important
methods of ActionForm are: validate () & reset ().
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 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() {}
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.
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">
<forward name="success" path="/success.jsp"/>
<forward name="failure" path="/error.jsp"/>
</action>
</action-mappings>
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.
In which method of Action class
the business logic is executed?
In the execute() method of
Action class the business logic is executed.
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception ;
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
What design patterns are used
in Struts?
Struts is
based on model 2 MVC (Model-View-Controller) architecture. Struts controller
uses the command design pattern and the
action classes use the adapter design pattern. The process() method of the RequestProcessor uses the template method design pattern. Struts also implement the following J2EE design
patterns.
- Service to Worker
- Dispatcher View
- Composite View (Struts Tiles)
- Front Controller
- View Helper
- Synchronizer Token
Can we have more than one struts-config.xml file for a single Struts application?
Yes, we can
have more than one struts-config.xml for a single Struts application. They can
be configured as follows:
<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>
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.
What are the different kinds of actions in Struts?
The different
kinds of actions in Struts are:
- ForwardAction
- IncludeAction
- DispatchAction
- LookupDispatchAction
- SwitchAction
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.
How to use DispatchAction?
To use the
DispatchAction, follow these steps:
- Create a class that extends
DispatchAction (instead of Action)
- 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.
- Do not override execute() method –
Because DispatchAction class itself provides execute() method.
- Add an entry to struts-config.xml
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 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
don’t have to write your own Action class. You just have to set up the struts-config file properly
to use ForwardAction.
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.
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.
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.
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.
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 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.
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> element’s <forward> takes precedence.
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.
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.DynaActionForminstead of some subclass ofActionForm
<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
Actionsubclass that uses your form bean: - import
org.apache.struts.action.DynaActionForm - downcast the
ActionFormparameter inexecute()to aDynaActionForm - access the form fields with
get(field)rather thangetField()
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"));
}
...........
How to display validation
errors on jsp page?
<html:errors/> tag displays
all the errors. <html:errors/> iterates over ActionErrors request attribute.
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
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>
What are differences between
<bean:message> and <bean:write>
<bean:message>: is used to retrieve
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"/>
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 yourstruts-config.xmlor 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"/>
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.getParameter( .. ).
- DynaActionForm construction at
runtime requires a lot of Java Reflection (Introspection) machinery that
can be avoided.
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 to struts-config.xml.
<message-resources parameter="com.login.struts.ApplicationResources"/>
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
What is a synchronizer token
pattern in Struts or how will you protect your Web against multiple submissions?
Web designers
often face the situation where a form submission must be protected against
duplicate or multiple
submissions. This situation typically occurs when
the user clicks on submit button more than once before the
response is sent
back or client access a page by returning to the previously book marked page.
􀂃
The simplest solution that some sites use is that displaying a warning message
“Wait for a response after
submitting and
do not submit twice.
􀂃
In the client only strategy, a flag is set on the first submission and from
then onwards the submit button is
disabled based
on this flag. Useful in some situations but this strategy is coupled to the
browser type and
version etc.
􀂃
For a server-based solution the J2EE pattern synchroniser token pattern can
be applied. The basic
idea is to:
1. Set a token
in a session variable on the server side before sending the transactional page
back to
the client.
2. The token is
set on the page as a hidden field. On submission of the page first check for
the
presence of a
valid token by comparing the request parameter in the hidden field to the token
stored
in the session.
If the token is valid continue processing otherwise take other alternative
action. After
testing the
token must be reset to null.
The synchroniser
token pattern is implemented in Struts. How do we implement the alternate
course of action
when the second
clicks on submit button will cancel the response from the first click. The
thread for the first click
still runs but
has no means of sending the response back to the browser. This means the
transaction might have
gone through
without notifying the user. The user might get the impression that transaction has
not gone
through.
Struts support
for synchronisation comes in the form of:
ActionServlet.saveToken(HttpRequest) and
ActionServlet.isTokenValid(HttpRequest) etc
How do you implement
internationalization in Struts?
Internationalization
is built into Struts framework. In the JSP page set the code as shown below: CO
<%@ taglib
uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib
uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib
uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<html:html locale="true">
<head>
<title>i18n</title>
</head>
<body>
<h2><bean:message
key="page.title"/></h2>
</body>
</html:html>
Now we need to
create an application resource file named ApplicationResource.properties.
page.title=Thank
you for visiting!
Now in Italian,
create an application resource file named ApplicationResource_it.properties.
page.title=Grazie
per la vostra visita!
Finally, add reference to the appropriate resource file in the
struts-config.xml.
What is an action mapping in
Struts? How will you extend Struts?
A 115: An action mapping is a
configuration file (struts-config.xml) 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.
How will you extend Struts?
Struts is not
only a powerful framework but also very extensible. You can extend Struts in
one or more of the
following ways:
PlugIn: Define your own PlugIn class if you
want to execute some init() and destroy() methods during the
application
startup and shutdown respectively. Some services like loading configuration
files, initialising
applications
like logging, auditing, etc can be carried out in the init() method.
RequestProcessor:
You can create your own
RequestProcessor by extending the Struts RequestProcessor.
For example you
can override the processRoles(req, res, mapping) in your extended class if you
want to query
the LDAP server
for the security authorization etc.
ActionServlet: You can extend the ActionServlet
class if you want to execute your business logic at the
application
startup or shutdown or during individual request processing. You should take
this approach only
when the above mentioned approaches are not feasible.
What design patterns are used
in Struts? DP
Struts
is based on model 2 MVC (Model-View-Controller) architecture. Struts controller
uses the command
design pattern (Refer Q11 in How would you go
about section) and the action classes use the adapter design
pattern.
How you will make available any
Message Resources Definitions file to the
Struts Framework Environment?
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” />
Why aren’t
Servlets used for presentation tier?
The answer lies
in the separation of concerns essential in real world J2EE projects. HTML
formatting and rendering is the concern of page author who most likely does not
know Java. So, the question arises, how
to separate these two concerns intermingled in Servlets? JSPs are the answer to
this dilemma. JSPs are servlets in disguise!
Presentation
Logic and Business Logic – What’s the difference?
The term Business Logic refers to the middle tier logic – the core of the system usually implemented as Session EJBs. The code that controls the JSP navigation, handles user inputs and invokes appropriate business logic is referred to as Presentation Logic. The actual JSP – the front end to the user contains html and custom tags to render the page and as less logic as possible. A rule of thumb is the dumber the JSP gets, the easier it is to maintain. In reality however, some of the presentation logic percolates to the actual JSP making it tough to draw a line between the two.
What is Struts?
Struts is a Java MVC framework for building web applications on the J2EE platform.
J2EE Platform
J2EE is a platform for executing server
side Java applications
The J2EE
application servers provide the infrastructure services such as threading,
pooling and transaction management out of the box. The application developers
can thus concentrate on implementing business logic.
J2EE Application Servers run in the
Java Virtual Machine (JVM) sandbox. They expose the standard J2EE interfaces to
the application developers.
Two three of
applications can be developed and deployed on J2EE application servers – Web
applications and EJB applications. These applications are deployed and executed
in container”s. J2EE specification defines containers for managing the
lifecycle of server side components.
The third one is an application conforming
to J2EE Connector Architecture (J2CA).
There are two
types of containers - Servlet containers and EJB containers. Servlet containers
manage the lifecycle of web applications and EJB containers manage the
lifecycle of EJBs.
J2EE
web application
Any web
application that runs in the servlet container is called a J2EE web application.
The servlet container implements the Servlet and JSP specification. It provides
various entry points for handling the request originating from a web browser.
There are three entry points for the browser into the J2EE web application -
Servlet, JSP and Filter.
The servlet
container becomes aware of Servlets and Filters when they are declared in a
special file called web.xml. A J2EE web application has exactly one web.xml file.
The web application is deployed into the servlet container by bundling it in
zipped archive called Web ARchive – commonly referred to as WAR file.
I.
Presentation
Tier Strategies
Technologies used for the presentation
tier can be roughly classified into three categories:
_ Markup based Rendering (e.g. JSPs)
_ Template based Transformation (e.g.
Velocity, XSLT)
_ Rich content (e.g. Macromedia Flash, Flex, Laszlo)
NOTE: Struts can be used as the controller
framework for any of the view generation strategies. Struts can be combined
with JSPs – the most popular option among developers. Struts can also be
combined with Velocity templating or XSLT. Struts is also an integral part of
Macromedia Flex. Lazlo and Struts can be
combined to deliver rich internet applications.
II.
Model
1 Architecture
In Model 1, the browser directly
accesses JSP pages. In other words, user requests are handled directly by the
JSP.
Let us illustrate the operation of
Model 1 architecture with an example. Consider a HTML page with a hyperlink to
a JSP. When user clicks on the hyperlink, the JSP is directly invoked. The
servlet container parses the JSP and executes the resulting Java servlet. The
JSP contains embedded code and tags to access the Model JavaBeans. The Model
JavaBeans contains attributes for holding the HTTP request parameters from the
query string. In addition it contains logic to connect to the middle tier or
directly to the database using JDBC to get the additional data needed to
display the page. The JSP is then rendered as HTML using the data in the Model
JavaBeans and other Helper classes and tags.
III.
Model
2 Architecture
The main difference between Model 1 and
Model 2 is that in Model 2, a controller handles the user request instead of
another JSP. The controller is implemented as a Servlet. The following steps
are executed when the user submits the request.
- The Controller Servlet handles the user’s request.
(This means the hyperlink in the JSP should point to the controller
servlet).
- The Controller
Servlet then instantiates appropriate JavaBeans based on the request
parameters (and optionally also based on session attributes).
- The Controller
Servlet then by itself or through a controller helper communicates with
the middle tier or directly to the database to fetch the required data.
- The Controller sets the resultant JavaBeans (either
same or a new one) in one of the following contexts – request, session or
application.
- The controller
then dispatches the request to the next view based on the request URL.
- The View uses
the resultant JavaBeans from Step 4 to display data.
IV.
Model
1 Vs Model 2 MVC Architecture
The model-view-controller design
pattern, also known as Model 2 in J2EE application programming, is a
well-established design pattern for programming. Table 1 summarizes the three
main components of MVC.
|
Table 1.
Summary of MVC components |
||
|
|
Purpose |
Description |
|
Model |
Maintain data |
Business logic plus one or more data
sources such as a relational database. |
|
View |
Display all or a portion of the data |
The user interface that displays
information about the model to the user. |
|
Controller |
Handle events that affect the model
or view |
The flow-control mechanism means by
which the user interacts with the application. |
The Model 1 and Model 2 architectures
both separate content generation (business logic) from the content presentation
(HTML formatting). Model 2 differs from Model 1 in the location where the bulk
of the request processing is performed: by a controller rather than in the JSP
pages.
In the JSP Model 1 architecture, the
JSP page alone processes the incoming request and replies to the client, as
shown in Figure 1.
Figure 1. JSP Model 1 architecture
In this three-tier architecture, a JSP
page and a Java bean are on an application server, and a data store and the
business logic are on a data server.
- The browser sends a request to a
JSP page.
- The JSP page communicates with a
Java bean.
- The Java bean is connected to a
database.
- The JSP page responds to the
browser.
In the JSP Model 2 architecture, the
servlet processes the request, creates any beans or objects used by the JSP
file, and forwards the request, as shown in Figure 2.
Figure 2. JSP Model 2 architecture
In this three-tier architecture, a
servlet and a JSP page are on an application server, and a data store and the
business logic are on a data server.
- The browser sends a request to a
servlet.
- The servlet instantiates a Java
bean that is connected to a database.
- The servlet communicates with a
JSP page.
- The JSP page communicates with the
Java bean.
- The JSP page responds to the
browser.
Table 2 presents criteria to help you
determine when Model 1 or Model 2 is likely to be more appropriate:
|
Table 2.
Guidelines for using Model 1 or Model 2 |
||
|
Criterion |
Model 1 |
Model 2 |
|
Type of Web application |
Simple |
Complex |
|
Nature of developer task |
Quick prototyping |
Creating an application to be
modified and maintained |
|
Who is doing the work |
View and controller being done by the
same team |
View and controller being done by
different teams |
V.
First
look at Struts
Listing 1.2 Sample ActionForm
public class MyForm extends
ActionForm {
private
String firstName;
private String lastName;
public MyForm() {
firstName = “”; lastName = “”;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String s) {
this.firstName = s;
}
public String getLastName() {
return lastName;
}
public void setLastName(String s) {
this.lastName = s;
}
}
In Struts, there
is only one controller servlet for the entire web application. This controller
servlet is called ActionServlet and resides in the package org.apache.struts.action.
It intercepts every client request and populates an ActionForm from the HTTP
request parameters. ActionForm is a
normal JavaBeans class. It has several attributes corresponding to the HTTP
request parameters and getter, setter methods for those attributes. You have to
create your own ActionForm for every HTTP request handled through the Struts framework
by extending the org.apache.struts.action.ActionForm class. Consider the
following HTTP request for App1 web application – http://localhost:8080/App1/create.do?firstName=John&lastName=Doe.
The
ActionForm class
for this HTTP request is shown in Listing 1.2. The class MyForm extends the
org.apache.struts.action.ActionForm class and contains two attributes –
firstName and lastName. It also has getter and setter methods for these
attributes. For the lack of better terminology, let us coin a term to describe
the classes such as ActionForm – View Data Transfer Object. View Data Transfer
Object is an object that holds the data from html page and transfers it around
in the web tier framework and application classes.
The
ActionServlet then instantiates a Handler. The Handler class name is obtained
from an XML file based on the URL path information. This XML file is referred
to as Struts configuration file and by default named as struts-config.xml. The
Handler is called Action in the Struts terminology. And you guessed it right! This
class is created by extending the Action class in
org.apache.struts.action
package. The Action class is abstract and defines a single method called
execute(). You override this method in your own Actions and invoke the business
logic in this method. The execute() method returns the name of next view (JSP)
to be shown to the user. The ActionServlet forwards to the selected view.
Struts components
- All the core components of Struts
framework belong to Controller category.
- Struts has no components in the Model
category.
- Struts has only auxiliary components in
View category. A collection of custom tags making it easy to interact with
the controller. The View category is neither the core of Struts framework
nor is it necessary. However it is a helpful library for using Struts
effectively in JSP based rendering.
View Category: The View category contains utility classes – variety of custom
tags making it easy to interact with the controller. It is not mandatory to use
these utility classes. You can replace it with classes of your own. However when
using Struts Framework with JSP, you will be reinventing the wheel by writing
custom tags that mimic Struts view components. If you are using Struts with
Cocoon or Velocity, then have to roll out your own classes for the View category.
Model Category: Struts does not offer any components in the Model Category.
You are on you own in this turf. This is probably how it should be. Many
component models (CORBA, EJB) are available to implement the business tier.
Your model components are as unique as your business and should not have any
dependency on a presentation framework like Struts. This philosophy of limiting
the framework to what is absolutely essential and helpful and nothing more has
prevented bloating and made the Struts framework generic and reusable.
NOTE: Some people argue that ActionForm is the model component. However ActionForm is really part of the controller. The Struts documentation also speaks along similar lines. It is just View Data Transfer Object – a regular JavaBeans that has dependencies on the Struts classes and used for transferring the data to various classes within the controller.
Struts
request lifecycle
Struts controller classes – ActionServlet, RequestProcessor, ActionForm, Action, ActionMapping and ActionForward – all residing in org.apache.struts.action
package.
ActionServlet
The central component of the Struts
Controller is the ActionServlet. It is a concrete class and extends the
javax.servlet.HttpServlet. It performs two important things.
1. On startup, its reads the Struts
Configuration file and loads it into memory in the init() method.
2. In the doGet() and doPost() methods,
it intercepts HTTP request and handles it appropriately.
The name of the Struts Config file can
be configured in web.xml. The web.xml entry for configuring the ActionServlet
and Struts Config file is as follows.
<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/config/myconfig.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
In the above snippet, the Struts Config
file is present in the WEB-INF/config directory and is named myconfig.xml. The
ActionServlet takes the Struts Config file name as an init-param. At startup,
in the init() method, the ActionServlet reads the Struts Config file and
creates appropriate Struts configuration objects (data structures) into memory.
Like any other servlet, ActionServlet
invokes the init() method when it receives the first HTTP request from the
caller. Loading Struts Config file into configuration objects is a time
consuming task. If the Struts configuration objects were to be created on the
first call from the caller, it will adversely affect performance by delaying
the response for the first user. The alternative is to specify load-on-startup
in web.xml as shown above. By specifying load-onstartup to be 1, you are
telling the servlet container to call the init() method immediately on startup
of the servlet container.
The second task that the ActionServlet
performs is to intercept HTTP requests based on the URL pattern and handles
them appropriately. The URL pattern can be either path or suffix. This is
specified using the servlet-mapping in web.xml. An example of
suffix mapping is as follows.
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
If the user types
http://localhost:8080/App1/submitCustomerForm.do in the browser URL bar, the
URL will be intercepted and processed by the ActionServlet since the URL has a
pattern *.do, with a suffix of "do”.
Once the ActionServlet intercepts the
HTTP request, it doesn’t do much. It delegates the request handling to another
class called RequestProcessor by invoking its process()method. Figure 2.1 shows
a flowchart with Struts controller components collaborating to handle a HTTP request
within the RequestProcessor’s process() method.
RequestProcessor
and ActionMapping
The RequestProcessor does the following
in its process() method:
Step 1: The RequestProcessor first retrieves appropriate XML block
for the URL from struts-config.xml. This XML block is referred to as ActionMapping
in Struts terminology. A sample ActionMapping from the Struts configuration
file looks as follows.
<action path="/submitDetailForm"
type="mybank.example.CustomerAction"
name="CustomerForm"
scope="request"
validate="true"
input="CustomerDetailForm.jsp">
<forward name="success"
path="ThankYou.jsp"
redirect=”true”/>
<forward name="failure"
path="Failure.jsp" />
</action>
Step 2: The RequestProcessor looks up the configuration file for the
URL pattern /submitDetailForm. (i.e. URL path without the suffix do)
and finds the XML block (ActionMapping) shown above. The type attribute
tells Struts which Action class has to be instantiated. The XML block also
contains several other attributes. Together these constitute the JavaBeans
properties of the ActionMapping instance for the path /submitDetailForm.
The above ActionMapping tells Struts to map the URL request with the
path /submitDetailForm to the class mybank.example.CustomerAction.
Since each HTTP request is
distinguished from the other only by the path, there should be one and
only one ActionMapping for every path attribute. Otherwise Struts
overwrites the former ActionMapping with the latter.
ActionForm
Another attribute in the ActionMapping
that you should know right away is name. It is the logical name of the ActionForm
to be populated by the RequestProcessor. After selecting the ActionMapping,
the RequestProcessor instantiates the ActionForm. However it has to know
the fully qualified class name of the ActionForm to do so. This is where
the name attribute of ActionMapping comes in handy. The name attribute
is the logical name of the ActionForm. Somewhere else in struts-config.xml,
you will find a declaration like this:
<form-bean name="CustomerForm"
type="mybank.example.CustomerForm"/>
This form-bean declaration associates a
logical name CustomerForm with the actual class
mybank.example.CustomerForm.
Step 3: The RequestProcessor instantiates the CustomerForm and puts it
in appropriate scope – either session or request. The RequestProcessor determines
the appropriate scope by looking at the scope attribute in the same ActionMapping.
Step 4: Next, RequestProcessor iterates through the HTTP request
parameters and populates the CustomerForm properties of the same name as the
HTTP request parameters using Java Introspection. (Java Introspection is a
special form of Reflection using the JavaBeans properties. Instead of directly
using the reflection to set the field values, it uses the setter method to set
the field value and getter method to retrieve the field value.)
Step 5: Next, the RequestProcessor checks for the validate attribute
in the ActionMapping. If the validate is set to true, the
RequestProcessor invokes the validate() method on the CustomerForm instance.
This is the method where you can put all the html form data validations. For
now, let us pretend that there were no errors in the validate() method and
continue. We will come back later and revisit the scenario when there are
errors in the validate() method.
Step 6: The RequestProcessor instantiates the Action class specified
in the ActionMapping (CustomerAction) and invokes the execute() method on the
CustomerAction instance.
Action
The
RequestProcessor instantiates the Action class specified in the ActionMapping CustomerAction)
and invokes the execute() method on the CustomerAction instance. The signature
of the execute method is as follows.
public ActionForward execute(ActionMapping
mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws
Exception
Apart from the HttpServletRequest and
HttpServletResponse, the ActionForm is also available in the Action instance.
This is what the ActionForm was meant for; as a convenient container to hold
and transfer data from the http request parameter to other components of the
controller, instead of having to look for them every time in the http request.
The execute() method itself should not
contain the core business logic irrespective of whether or not you use EJBs or
any fancy middle tier.
The RequestProcessor creates an
instance of the Action (CustomerAction), if one does not exist already. There
is only one instance of Action class in the application. Because of this you
must ensure that the Action class and its attributes if any are thread-safe.
General rules that apply to Servlets hold good. The Action class should not
have any writable attributes that can be changed by the users in the execute()
method.
ActionForward
The execute() method returns the next
view shown to the user. ActionForward is the class that encapsulates the next
view information. Struts, being the good framework it is, encourages you not to
hardcode the JSP names for the next view. This association of the logical name
and the physical JSP page is encapsulated in the ActionForward instance
returned from the execute method.
Comments
Post a Comment