Struts
1.1
- Introduction to MVC
- Overview of MVC Architecture 63
- Applying MVC in Servlets and JSP
- View on JSP
- JSP Model 1 Architecture
- JSP Model 2 Architecture
- Limitation in traditional MVC approach
- MVC Model 2 Architecture
- The benefits
- Application flow
- Overview of Struts Framework 66
- Introduction to Struts Framework
- Struts Architecture
- Front Controller Design Pattern
- Controller servlet - ActionServlet
- Action objects
- Action Form objects
- Action mappings
- Configuring web.xml file and
struts-config.xml file
- Struts – View components
- Composite View
- Building page from templates
- Jsp:include Vs struts template mechanism
- Bean tags
- Html tags
- Logic tags
- Template tags
- Struts – Controller components
- Action classes
- ActionServlet
- Struts data source
- Advanced Struts
- Accessing Application Resource File
- Use of Tokens
- Accessing Indexed properties
- Forward Vs Redirect
- Dynamic creating Action Forwards
- Struts 1.1
- DynaActionForm
- DynaValidatorActionForm
Validating Input Data
Declarative approach
Using Struts Validator
Configuring the Validator
Specifying validation rules
Client side validation
Using Struts Validator
Configuring the Validator
Specifying validation rules
Client side validation
- Plugins
- I18N
(InternationalizatioN)
Specifying a
resource bundle
Generating Locale specific messages
Generating Locale specific messages
- Tiles
Introduction to MVC(Model View Controler)
Struts : Struts is an open source framework from
Jakartha Project designed for developing the web applications with Java SERVLET
API and Java Server Pages Technologies.Struts conforms the Model View
Controller design pattern. Struts package provides unified reusable components
(such as action servlet) to build the user interface that can be applied to any
web connection. It encourages software
development following the MVC design pattern.
Overview of MVC Architecture
The MVC design pattern divides applications into
three components:
- The Model maintains the state and
data that the application represents .
- The View allows the display of
information about the model to the user.
- Data SourcesGServices_UsersJSecurityOperational managementCommunication
UI
Components
|
Service
Interfaces
|
Data
Access Logic Components
|
Service
Agents
|
Business
Workflows
|
Business
Components
|
Business
Entities
|
UI
Process Components
|
In Struts,
the view is handled by JSPs and presentation components, the model is
represented by Java Beans and the controller uses Servlets to perform its
action.
By
developing a familiar Web-based shopping cart, you'll learn how to utilize the Model-View-Controller
(MVC) design pattern and truly separate presentation from content when using
Java Server Pages.
Applying MVC in Servlets and JSP
Many
web applications are JSP-only or Servlets-only. With JSP, Java code is embedded
in the HTML code; with Servlets the Java code calls println methods to generate
the HTML code. Both approaches have their advantages and drawbacks; Struts
gathers their strengths to get the best of their association.
Below you will find one example on registration form
processing using MVC in Servlets and JSP:
Controller
Servlet
|
|
Reg_master
|
Confirm.jsp
|
Error.jsp
|
If()
|
If()
|
Reg JSP
|
User
|
- In the above application Reg.jsp act as view
accepts I/P from client and submits to Controller Servlet.
- Controller Servlet validates the form data, if
valid, stores the data into DB
- Based on the validation and DB operations
Controller Servlet decides to respond either Confirm.jsp or Error.jsp to
client’s browser.
- When the Error.jsp is responded, the page must
include all the list of errors with detailed description.
- The above shown application architecture is
the model for MVC.
- IF MVC Model 2 wants to be implemented in your
application business logic and model operations must be separated from
controller program.
View on JSP
The early JSP specification follows two approaches for building
applications using JSP technology. These two approaches are called as JSP Model
1 and JSP Model 2 architectures.
JSP Model 1 Architecture
In
Model 1 architecture the JSP page is alone responsible for processing the
incoming request and replying back to the client. There is still separation of
presentation from content, because all data access is performed using beans.
Although the JSP Model 1 Architecture is more suitable for simple applications,
it may not be desirable for complex implementations.
JSP Model 2 Architecture - MVC
The Model 2 Architecture is an approach for serving dynamic content,
since it combines the use of both Servlets and JSP. It takes advantages of the
predominant strengths of both technologies, using JSP to generate the
presentation layer and Servlets to perform process-intensive tasks. Here
servlet acts as controller and is in
charge of request processing and the creation of any beans or objects used by
the JSP as well as deciding depending on the user’s actions, which JSP page to
forward the request to. Note that there is no processing logic within the JSP
page itself; it is simply responsible for retrieving any objects or beans that
may have been previously created by the servlet, and extracting the dynamic
content from that servlet for insertion within static templates.
Limitation in traditional MVC approach
The main limitation in the traditional MVC
approach is, in that there is no separation of business logic (validation/
conditions/ anything related to business rules) from controller (is responsible
for controlling of the application flow by using static/dynamic request
dispatcher.
MVC Model 2 Architecture is Model
View Controller
Browser
|
Servlet
Controller
|
Servlet
Validator
|
Servlet
Model
|
JSP
View
|
Beans
|
1
|
2
|
3
|
4
|
5
|
6
|
7
|
User
|
Pass
|
Login
|
- Client submits login request to servlet
application
- Servlet application acts as controller it
first decides to request validator another servlet program which is
responsible for not null checking (business rule)
- control comes to controller back and based on
the validation response, if the response is positive, servlet controller
sends the request to model
- Model requests DB to verify whether the
database is having the same user name and password, If found login
operation is successful
- Beans are used to store if any data retrieved
from the database and kept into HTTPSession
- Controller then gives response back to
response JSP (view) which uses the bean objects stored in HTTPSession
object
- and prepares presentation response on to the
browser
Overview of Struts Framework
Introduction to Struts Framework
The goal of this project is to provide
an open source framework for building Java web applications. The core of the
Struts framework is a flexible control layer based on standard technologies like
Java Servlets, JavaBeans, Resource Bundles, and XML, as well as various Jakarta
Commons packages. Struts encourages application architectures based on the
Model 2 approach, a variation of the classic Model-View-Controller (MVC) design paradigm.
Struts
provides its own Controller component and
integrates with other technologies to provide the Model and the View.
·
For the Model, Struts can
interact with standard data access technologies, like JDBC and EJB, as well as
most any third-party packages, like Hibernate, iBATIS, or Object Relational
Bridge.
·
For the View, Struts works
well with Java Server Pages, including JSTL and JSF, as well as Velocity
Templates, XSLT, and other presentation systems.
·
For Controller, ActionServlet and ActionMapping -
The Controller portion of the application is focused on
receiving requests from the client deciding what business logic function is to
be performed, and then delegating responsibility for producing the next phase
of the user interface to an appropriate View component. In Struts, the primary
component of the Controller is a servlet of class
ActionServlet
.
This servlet is configured by defining a set of ActionMappings
.
An ActionMapping defines a path
that is matched against the
request URI of the incoming request, and usually specifies the fully qualified
class name of an Action class. Actions encapsulate the business logic,
interpret the outcome, and ultimately dispatch control to the appropriate View
component to create the response.
The Struts project was launched in May 2000 by Craig McClanahan to
provide a standard MVC framework to the Java community. In July 2001.
In the MVC design pattern, application
flow is mediated by a central Controller. The Controller delegates’ requests -
in our case, HTTP requests - to an appropriate handler. The handlers are tied
to a Model, and each handler acts as an adapter between the request and the
Model. The Model represents, or encapsulates, an application's business logic
or state. Control is usually then forwarded back through the Controller to the
appropriate View. The forwarding can be determined by consulting a set of
mappings, usually loaded from a database or configuration file. This provides a
loose coupling between the View and Model, which can make applications
significantly easier to create and maintain.
Struts Architecture
Request.jsp
|
ActionServlet
|
Struts-config.xml
|
ActionForm
|
Action
|
Success
Response
|
Error
Response
|
J2EE
Component (EJB)
|
DB
|
Legacy
code
|
Front Controller
Context
The presentation-tier request handling
mechanism must control and coordinate processing of each user across multiple
requests. Such control mechanisms may be managed in either a centralized or
decentralized manner.
Problem
The
system requires a centralized access point for presentation-tier request
handling to support the integration of system services, content retrieval, view
management, and navigation. When the user accesses the view directly without
going through a centralized mechanism,
Two problems may occur:
§ Each view is
required to provide its own system services, often resulting in duplicate code.
§ View navigation
is left to the views. This may result in commingled view content and view
navigation.
Additionally, distributed control is more difficult
to maintain, since changes will often need to be made in numerous places.
Solution :
Use a controller as the initial point of
contact for handling a request. The controller manages the handling of the
request, including invoking security services such as authentication and
authorization, delegating business processing, managing the choice of an
appropriate view, handling errors, and managing the selection of content
creation strategies.
The controller provides a centralized entry point that controls and
manages Web request handling. By centralizing decision points and controls, the
controller also helps reduce the amount of Java code, called scriptlets,
embedded in the JavaServer Pages (JSP) page.
Centralizing control in the controller and reducing business logic in
the view promotes code reuse across requests. It is a preferable approach to
the alternative-embedding code in multiple views-because that approach may lead
to a more error-prone, reuse-by-copy- and-paste environment.
Typically, a controller coordinates with a dispatcher component. Dispatchers
are responsible for view management and navigation. Thus, a dispatcher chooses
the next view for the user and vectors control to the resource. Dispatchers may
be encapsulated within the controller directly or can be extracted into a
separate component.
While the Front Controller pattern suggests centralizing the handling of
all requests, it does not limit the number of handlers in the system, as does a
Singleton. An application may use multiple controllers in a system, each
mapping to a set of distinct services.
Structure
Below figure
represents the Front Controller class diagram pattern.
Figure: Front Controller class diagram
Participants and Responsibilities
Below
figure shows the sequence diagram representing the Front Controller pattern. It
depicts how the controller handles a request.
Figure: Front Controller sequence diagram
Controller : The controller is the initial contact point for handling all requests in the system. The controller may delegate to a helper to complete authentication and authorization of a user or to initiate contact retrieval.
Dispatcher
:
A
dispatcher is responsible for view management and navigation, managing the choice
of the next view to present to the user, and providing the mechanism for
vectoring control to this resource.
A
dispatcher can be encapsulated within a controller or can be a separate
component working in coordination. The dispatcher provides either a static
dispatching to the view or a more sophisticated dynamic dispatching mechanism.
The
dispatcher uses the Request Dispatcher object (supported in the servlet
specification) and encapsulates some additional processing.
Helper :
A helper
is responsible for helping a view or controller complete its processing. Thus,
helpers have numerous responsibilities, including gathering data required by
the view and storing this intermediate model, in which case the helper is
sometimes referred to as a value bean. Additionally, helpers may adapt this
data model for use by the view. Helpers can service requests for data from the
view by simply providing access to the raw data or by formatting the data as
Web content.
A
view may work with any number of helpers, which are typically implemented as
JavaBeans components (JSP 1.0+) and custom tags (JSP 1.1+). Additionally, a
helper may represent a Command object, a delegate, or an XSL Transformer, which
is used in combination with a stylesheet to adapt and convert the model into
the appropriate form.
View : A view represents and
displays information to the client. The view retrieves information from a
model. Helpers support views by encapsulating and adapting the underlying data
model for use in the display.
Controller Servlet – Action Servlet
For those of you familiar with MVC architecture,
the ActionServlet represents the C - the controller. The job of the controller
is to:
·
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, and
·
select the proper view to respond to the user.
The
Struts controller delegates most of this grunt work to the Request Processor and Action classes.
In addition to being the front controller for your application, the
ActionServlet instance also is responsible for initialization and clean-up of
resources. When the controller initializes, it first loads the application
config corresponding to the "config" init-param. It then goes through
an enumeration of all
init-param
elements, looking for those elements who's name starts with config/
. For each of these elements, Struts loads the
configuration file specified by the value of that init-param
, and assigns a "prefix" value to that
module's ModuleConfig instance consisting of the piece of the init-param
name following "config/". For example,
the module prefix specified by the init-param config/foo
would be "foo". This is important to
know, since this is how the controller determines which module will be given
control of processing the request. To access the module foo, you would use a
URL like: http://localhost:8080/myApp/foo/someAction.do
For
each request made of the controller, the method
process(HttpServletRequest,
HttpServletResponse)
will be called. This method simply
determines which module should service the request and then invokes that
module's RequestProcessor's process method, passing the same request and
response.
Request
Processor :
The RequestProcessor is where the majority
of the core processing occurs for each request. Let's take a look at the helper
functions the process method invokes in-turn:
processPath |
Determine the path that invoked us. This will be
used later to retrieve an ActionMapping.
|
processLocale |
Select a locale for this request, if one hasn't
already been selected, and place it in the request.
|
processContent |
Set the default content type (with optional
character encoding) for all responses if requested.
|
processNoCache |
If appropriate, set the following response
headers: "Pragma", "Cache-Control", and
"Expires".
|
processPreprocess |
This is one of the "hooks" the
RequestProcessor makes available for subclasses to override. The default
implementation simply returns
true . If you subclass
RequestProcessor and override processPreprocess you should either return true
(indicating process should continue processing the request) or false
(indicating you have handled the request and the process should return) |
processMapping |
Determine the ActionMapping associated with this
path.
|
processRoles |
If the mapping has a role associated with it, ensure
the requesting user is has the specified role. If they do not, raise an error
and stop processing of the request.
|
processActionForm |
Instantiate (if necessary) the ActionForm
associated with this mapping (if any) and place it into the appropriate
scope.
|
processPopulate |
Populate the ActionForm associated with this
request, if any.
|
processValidate |
Perform validation (if requested) on the
ActionForm associated with this request (if any).
|
processForward |
If this mapping represents a forward, forward to
the path specified by the mapping.
|
processInclude |
If this mapping represents an include, include
the result of invoking the path in this request.
|
processActionCreate |
Instantiate an instance of the class specified by
the current ActionMapping (if necessary).
|
processActionPerform |
This is the point at which your action's
perform
or execute method will be called. |
processForwardConfig |
Finally, the process method of the
RequestProcessor takes the ActionForward returned by your Action class, and
uses to select the next resource (if any). Most often the ActionForward leads
to the presentation page that renders the response.
|
Action class
The
Action
class defines two methods that could be executed depending on your servlet
environment:
public ActionForward execute(ActionMapping mapping,
ActionForm form,
ServletRequest request,
ServletResponse response)
throws Exception;
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception;
Since the majority of Struts projects are
focused on building web applications, most projects will only use the
"HttpServletRequest" version. A non-HTTP execute() method has been
provided for applications that are not specifically geared towards the HTTP
protocol.
The
goal of an
Action
class is to process a request, via its execute
method, and return an ActionForward
object that identifies where control should be forwarded (e.g. a JSP, Tile
definition, Velocity template, or another Action) to provide the appropriate
response. In the MVC/Model 2 design pattern, a typical Action
class will often implement logic like the following in its execute
method:
·
Validate
the current state of the user's session (for example, checking that the user
has successfully logged on). If the
Action
class finds that no logon exists, the
request can be forwarded to the presentation page that displays the username
and password prompts for logging on. This could occur because a user tried to
enter an application "in the middle" (say, from a bookmark), or
because the session has timed out, and the servlet container created a new one.
·
If
validation is not complete, validate the form bean properties as needed. If a
problem is found, store the appropriate error message keys as a request
attribute, and forward control back to the input form so that the errors can be
corrected.
·
Perform
the processing required to deal with this request (such as saving a row into a
database). This can
be done by logic code embedded within the
Action
class itself, but should generally be performed by calling
an appropriate method of a business logic bean.
·
Update
the server-side objects that will be used to create the next page of the user
interface (typically request scope or session scope beans, depending on how
long you need to keep these items available).
·
Return
an appropriate
ActionForward
object that identifies the presentation
page to be used to generate this response, based on the newly updated beans.
Typically, you will acquire a reference to such an object by calling findForward
on either the ActionMapping
object you received (if you are using a
logical name local to this mapping), or on the controller servlet itself (if
you are using a logical name global to the application).
In Struts 1.0, Actions called a
perform
method instead of the now-preferred execute
method. These methods use the same parameters and differ only in which
exceptions they throw. The elder perform
method throws SerlvetException
and IOException
.
The new execute
method simply throws Exception
.
The change was to facilitate the Declarative Exception handling feature
introduced in Struts 1.1.
The
perform
method may still be used in Struts 1.1 but is deprecated. The Struts 1.1 method
simply calls the new execute
method and wraps any Exception
thrown as a ServletException
.
Action Form class
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. ActionForms can be stored in either the
session (default) or request scopes. If they're in the session it's important
to implement the form's
reset
method to initialize the form before each use. Struts sets the ActionForm's
properties from the request parameters and sends the validated form to the
appropriate Action's execute
method.
When
you code your
ActionForm
beans, keep the following principles in mind:
·
The
ActionForm
class itself requires no specific methods
to be implemented. It is used to identify the role these particular beans play
in the overall architecture. Typically, an ActionForm
bean will have only property getter and
property setter methods, with no business logic.
·
The
ActionForm object also offers a standard validation mechanism. If you override
a "stub" method, and provide error messages in the standard
application resource, Struts will automatically validate the input from the
form (using your method). See "Automatic Form
Validation"
for details. Of course, you can also ignore the ActionForm validation and
provide your own in the Action object.
·
Define a
property (with associated
getXxx
and setXxx
methods) for each field that is present in
the form. The field name and property name must match according to the usual
JavaBeans conventions (see the Javadoc for the java.beans.Introspector
class for a start on information about
this). For example, an input field named username
will cause the setUsername
method to be called.
·
Buttons
and other controls on your form can also be defined as properties. This can
help determine which button or control was selected when the form was
submitted. Remember, the ActionForm is meant to represent your data-entry form,
not just the data beans.
·
Think of
your ActionForm beans as a firewall between HTTP and the Action. Use the
validate
method to ensure all required properties
are present, and that they contain reasonable values. An ActionForm that fails
validation will not even be presented to the Action for handling.
·
You may
also place a bean instance on your form, and use nested property references.
For example, you might have a "customer" bean on your ActionForm, and
then refer to the property "customer.name" in your presentation page.
This would correspond to the methods
customer.getName()
and customer.setName(string
Name)
on your customer
bean. See the Tag Library Developer Guides for more about using nested syntax
with the Struts JSP tags.
·
Caution: If you nest an existing bean instance on
your form, think about the properties it exposes. Any public property on an
ActionForm that accepts a single String value can be set with a query string.
It may be useful to place beans that can affect the business state inside a
thin "wrapper" that exposes only the properties required. This
wrapper can also provide a filter to be sure runtime properties are not set to
inappropriate values.
No comments:
Post a Comment