Struts
Struts
is a open source framework which make building of the web applications easier
based on the java Servlet and JavaServer
pages technologies.
Struts framework was created by Craig R. McClanahan and donated to the Apache
Software Foundation in 2000. The Project now has several committers, and many
developers are contributing to overall to the framework.
Developing web application using struts frame work is fairly complex, but it
eases things after it is setup. It encourages software development following
the MVC design pattern. Many web applications are JSP-only or Servlets-only. With JSP and Servlets,
Java code is embedded in the HTML code and the Java code calls println methods to generate the HTML code respectively.
Both approaches have their advantages and drawbacks; Struts gathers their
strengths to get the best of their association.
Struts
is based on Model-View-Controller (MVC) design paradigm, it is an
implementation of JSP Model 2 Architecture. For more of Model-View-Controller
(MVC)clickhere.
Consists of 8 Top-Level Packagesand
approx 250 Classes and Interfaces.
Struts is a set of cooperating classes, servlets, and
JSP tags that make up a reusable MVC 2 design. This definition implies that
Struts is a framework, rather than a library, but Struts also contains an
extensive tag library and utility classes that work independently of the
framework.
The overview of struts
Client browser
An HTTP request from the client browser creates an event. The Web container
will respond with an HTTP response.
Controller
The controller is responsible for intercepting and translating user input into
actions to
be performed by the model. The controller is responsible for selecting the next
view based on user input and the outcome of model operations.The
Controller receives the request from the browser, and makes the decision where
to send the request. With Struts, the Controller is a command design pattern
implemented as a servlet. The struts-config.xml file configures the Controller.
Business logic
The business logic updates the state of the model and
helps control the flow of the application. With Struts this is done with an
Action class as a thin wrapper to the actual business logic.
Model
A model represents an application’s data and contains the logic for accessing
and manipulating that data. Any data that is part of the persistent state of
the application should reside in the model objects. The business objects update
the application state. ActionForm bean represents the
Model state at a session or request level, and not at a persistent level. Model
services are accessed by the controller for either querying or effecting a
change in the model state. The model notifies the view when a state change
occurs in the model.The JSP file reads information from
the ActionForm bean using JSP tags.
View
The view is responsible for rendering the state of the model. The presentation
semantics are encapsulated within the view, therefore model data can be adapted
for several different kinds of clients.The view modifies itself when a change in the model is communicated
to the view. A view forwards user input to the controller.The
view is simply a JSP file. There is no flow logic, no business logic, and no
model information -- just tags. Tags are one of the things that make Struts
unique compared to other frameworks like Velocity
MVC
The
MVC (Model-View-Controller) architecture the client request is first
intercepted by a servlet referred as controller servlet. this servlet
handles the initial processing of the request and determines which JSP page to
display next. Here the controller servlet is the
single point of entry, there is a clear sepration of
business logic, presentation output and request processing. MCV architecture is
a way of decomposing an application into three parts:
The model maintains
the state and data that the application represents.
The view allows the
display of information about the model to the user.
The controller allows
the user to manipulate the application.
the model, the view and the controller.
MVC was originally applied in the graphical user interaction model of input,
processing and output.
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.
Model
A model represents an application’s data and contains the logic for accessing
and manipulating that data. Any data that is part of the persistent state of
the application should reside in the model objects. The business objects update
the application state. ActionForm bean represents the
Model state at a session or request level, and not at a persistent level. Model
services are accessed by the controller for either querying or effecting a
change in the model state. The model notifies the view when a state change
occurs in the model.The JSP file reads information
from the ActionForm bean using JSP tags.
View
The view is responsible for rendering the state of the model. The presentation
semantics are encapsulated within the view, therefore model data can be adapted
for several different kinds of clients.The view modifies itself when a change in the model is communicated
to the view. A view forwards user input to the controller.The
view is simply a JSP or HTML file. There is no flow logic, no business logic,
and no model information -- just tags. Tags are one of the things that make
Struts unique compared to other frameworks like Velocity.
Controller
The controller is responsible for intercepting and translating user input into
actions to
be performed by the model. The controller is responsible for selecting the next
view based on user input and the outcome of model operations.The
Controller receives the request from the browser, and makes the decision where
to send the request. With Struts, the Controller is a command design pattern
implemented as a servlet. The struts-config.xml file configures the Controller.
Struts
can be found as a subproject of the
For Struts documentation, install notes, and downloads, see the Struts
Home page.
Installing Struts
In
order to do any Java development you need the Java Developer Kit. You can find
JDK1.4 at http://java.sun.com.
Just execute the installation executable and follow the instructions.
You will need to setup the PATH and the JAVA HOME variables;
Struts can also be found as a subproject of the
Copy the following JAR files, extracted from the Jakarta Struts archive, to the
/WEB-INF/lib directory:
struts.jar
commons-beanutils.jar
commons-collections.jar
commons-digester.jar
commons-logging.jar
commons-validator.jar
Copy the tld files you want to use in the /WEB-INF
directory:
struts-html.tld
struts-bean.tld
struts-logic.tld
struts-nested.tld
struts-template.tld
If you want to use tiles add the struts-tiles.tld also in the /WEB-INF directory.
Add struts-config.xml
file in the /WEB-INF directory
Fot configuring the struts for you application refer
to Configuring Struts.
For Struts documentation, install notes, and downloads, see the Struts
Home
Configuring Struts
Struts
framework use two related type of configuration file, which nust
be configured properly before and application will work correctly. Both configration files are XML based. The first one is the web
application deployment descriptor web.xml and the second one the Struts
configuration file, it is comonly named struts-config.xml.
Configuring web.xml
There are few Struts-specific configuration options
that you must configure within this file when using the struts framework.
Modify the web.xml file in /WEB-INF directory by
adding the .tld file you want to use like if you are
using struts-html.tld then
|
<taglib> |
|
|
|
<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri> |
|
</taglib> |
|
Configure
the ActionServlet that will receive all the incoming request for the appliation.
The two steps involved in configuring the Struts controller servlet
in the web.xml are, first to use the servlet element to configure the servlet
instance that can be latter mapped in the servlet
mapping element.
Using servlet element to configure the servlet class in web.xml
|
<web-app> |
|||
|
|
<sertvlet> |
||
|
|
|
|
<servlet-name>some name</servlet-name> |
|
|
|
|
<servlet-class>the class name</servlet-class> |
|
|
|
</sertvlet> |
|
|
</web-app> |
|||
|
|
|
|
|
Configure
servlet mapping
|
<web-app> |
|||
|
|
<sertvlet> |
||
|
|
|
|
<servlet-name>some name</servlet-name> |
|
|
|
|
<servlet-class>the class name</servlet-class> |
|
|
|
</sertvlet> |
|
|
|
|
<sertvlet-mapping> |
|
|
|
|
|
<servlet-name>some name</servlet-name> |
|
|
|
|
<url-pattern>*.do </url-pattern> |
|
|
|
</sertvlet-mapping> |
|
|
</web-app> |
|||
|
|
|
|
|
|
|
The
new features added to Struts 1.1 are
|
Struts Controller
The
controller is responsible for intercepting and translating user input into
actions to be performed by the model. The controller is responsible for
selecting the next view based on user input and the outcome of model
operations. The Controller receives the request from the browser,
invoke a business operation and coordinating the view to return to the client.
The controller is implemented by a java servlet, this servlet is centralized
point of control for the web application. 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.servlet.http.httpServlet
class. The ActionServlet class is not abstract and
therefore can be used as a concrete controller by your application.
The
controller is implemented by the ActionServlet class.
All incoming requests are mapped to the central controller in the deployment
descriptor as follows.
|
<servlet> |
|
|
|
<servlet-name>action</servlet-name> |
|
|
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class> |
|
</servlet> |
|
All request URIs with the pattern *.do are mapped to this servlet in the
deployment descriptor as follows.
|
<servlet-mapping> |
|
|
|
<servlet-name>action</servlet-name> |
|
|
<url-pattern>*.do</url-pattern> |
|
<url-pattern>*.do</url-pattern> |
|
A
request URI that matches this pattern will have the following form.
http://www.my_site_name.com/mycontext/actionName.do
The preceding mapping is called extension mapping, however, you can also
specify path mapping where a pattern ends with /* as shown below.
|
<servlet-mapping> |
|
|
|
<servlet-name>action</servlet-name> |
|
|
<url-pattern>/do/*</url-pattern> |
|
<url-pattern>*.do</url-pattern> |
|
A
request URI that matches this pattern will have the following form.
http://www.my_site_name.com/mycontext/do/action_Name
The
class org.apache.struts.action.requestProcessor
process the request from the controller. You can sublass
the RequestProcessor with your own version and modify
how the request is processed.
Once the controller receives a client request, it delegates the handling of the
request to a helper class. This helper knows how to execute the business
operation associated with the requested action. In the Struts framework this
helper class is descended of org.apache.struts.action.Action class. It acts as a
bridge between a client-side user action and business operation. The Action
class decouples the client request from the business model. This decoupling
allows for more than one-to-one mapping between the user request and an action.
The Action class also can perform other functions such as authorization,
logging before invoking business operation. the Struts
Action class contains several methods, but most important method is the
execute() method.
|
public ActionForward execute(ActionMapping
mapping, |
|
|
|
ActionForm form, HttpServletRequest request,
HttpServletResponse response) |
|
throws
Exception; |
|
The
execute() method is called by the controller when a
request is received from a client. The controller creates an instance of the
Action class if one doesn’t already exist. The strut framework will create only
a single instance of each Action class in 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. Each Action element is represented in memory by an
instance of the org.apache.struts.action.ActionMapping
class . The ActionMapping
object contains a path attribute that is matched against a portion of the URI
of the incoming request.
|
<action> |
|
|
|
path=
"/somerequest" |
|
|
type="com.somepackage.someAction" |
|
|
scope="request" |
|
|
name="someForm" |
|
|
validate="true" |
|
|
input="somejsp.jsp" |
|
|
<forward
name="Success" path="/action/xys"
redirect="true"/> |
|
|
<forward
name="Failure" path="/somejsp.jsp"
redirect="true"/> |
|
</action> |
|
Once
this is done the controller should determine which view to return to the
client. The execute method signature in Action class has a return type org.apache.struts.action.ActionForward class. The ActionForward class represents a destination to which the
controller may send control once an action has completed. Instead of specifying
an actual JSP page in the code, you can declaratively associate as action
forward through out the application. The action forward are specified in the
configuration file.
|
<action> |
|
|
|
path=
"/somerequest" |
|
|
type="com.somepackage.someAction" |
|
|
scope="request" |
|
|
name="someForm" |
|
|
validate="true" |
|
|
input="somejsp.jsp" |
|
|
<forward
name="Success" path="/action/xys"
redirect="true"/> |
|
|
<forward
name="Failure" path="/somejsp.jsp"
redirect="true"/> |
|
</action> |
|
The
action forward mappings also can be specified in a global section, independent
of any specific action mapping.
|
<global-forwards> |
|
|
|
<forward
name="Success" path="/action/somejsp.jsp"
/> |
|
|
<forward
name="Failure" path="/someotherjsp.jsp"
/> |
|
</global-forwards> |
|
Struts Model
A
model represents an application’s data and contains the logic for accessing and
manipulating that data. Any data that is part of the persistent state of the
application should reside in the model objects. The business objects update the
application state. ActionForm bean represents the
Model state at a session or request level, and not at a persistent level. Model
services are accessed by the controller for either querying or effecting a
change in the model state. The model notifies the view when a state change
occurs in the model.The JSP file reads information
from the ActionForm bean using JSP tags.
The Struts frame work doen't offer
much in the way pf building model components. The Enterprise JavaBeans (EJB),
Java Data Objects(JDO) and JavaBeans can be use as a
model. Struts frame work doesn't limit you to one particular model
implementation.
Struts View
The
view is responsible for rendering the state of the model. The presentation
semantics are encapsulated within the view, therefore model data can be adapted
for several different kinds of clients.The view modifies itself when a change in the model is communicated
to the view. A view forwards user input to the controller.The
view is simply a JSP or HTML file. There is no flow logic, no business logic,
and no model information -- just tags. Tags are one of the things that make
Struts unique compared to other frameworks like Velocity.
The view components typically employed in a struts application are
HTML
Data Transfer Objects
Struts ActionForms
JavaServer pages
Custom tags
Java resource bundles
Struts ActionForm
Struts ActionForm objects are used to pass client
input data back and forth between the user and the business layer. The
framework automatically collects the input from the request and passes this
data to an Action using a form bean, which is then passed to the business
layer.
Struts Tag Library
The
Struts framework provides a fairly rich set of framework components. It also
includes a set of tag libraries that are designed to interact intimately with
the rest o the framework. The customg tags provided
by Struts framework are grouped into four distinct libraries
1. HTML
2. Bean
3. Logic
4. Template
And a special library called Nested tag library.
Custom tags with in Struts HTML tag library
|
base |
-
renders an HTML base element |
|
button |
-
renders a button input fiels |
|
cancel |
-
renders a cancel button |
|
checkbox |
-
renders a checkbox input field |
|
errors |
- conditionnaly renders a set of accumulated error messages |
|
file |
-
renders a file select input field |
|
form |
-
defines an HTML form element |
|
frame |
-
renders an HTML frame element |
|
hidden |
-
renders a hidden field |
|
html |
-
renders an HTMl html
element |
|
image |
-
renders an input tag of type "image" |
|
img |
-
renders an HTMl img tag |
|
javascript |
- renderts JavaScript validation rules loaded by ValidationPlugin |
|
link |
-
renders an HTML anchoror hyperlink |
|
messages |
-
Conditionally displays a set of accumulated messages |
|
multibox |
-renders
multiple checkbox input fields |
|
option |
-
renders a select option |
|
options |
-
renders a collection of select options |
|
options
Collection |
- render
a collection of select options |
|
password |
-renders
apassword input field |
|
radio |
-renders
a radio button input field |
|
reset |
-renders
a rest button input field |
|
rewrite |
-
renders a URI |
|
select |
-renders
a select element |
|
submit |
-renders
a submi button |
|
text |
-renders
an input field of type "text" |
|
textarea |
-renders
an textarea input field |
Struts Example
Struts
is modeled after the MVC design pattern, you can follow a standard development
process for all of your Struts Web applications.
Identificaty of the application Views, the Controller
objects that will service those Views, and the Model
components being operated on.
1.
Define and create all of the Views, in relation to their purpose, that will
represent the user interface of our application. Add all ActionForms
used by the created Views to the struts-config.xml
file.
2. Create the components of the application’s Controller.
3. Define the relationships that exist between the Views and the Controllers
(struts-config.xml).
4. Make the appropriate modifications to the web.xml file, describe the Struts components to the Web application.
Lets
Start with step one. we will create the view file
named index.jsp
index.jsp
<%@ page language="java"
%>
<%@ taglib
uri="/WEB-INF/struts-html.tld"
prefix="html" %>
|
<html> |
||||
|
|
<html:form action="Name" name="nameForm" type="example.NameForm"> |
|||
|
|
|
<table
width="80%" border="0"> |
||
|
|
|
|
<tr> |
|
|
|
|
|
|
<td>Name:</td> |
|
|
|
|
|
<td><html:text property="name" /></td> |
|
|
|
|
</tr> |
|
|
|
|
|
<tr> |
|
|
|
|
|
|
<td><html:submit /></td> |
|
|
|
|
</tr> |
|
|
|
|
</table> |
||
|
|
</html:form> |
|||
|
</body> |
||||
We
have used some Struts-specific Form tag like <html:form /> instead of HTML tags.
In the Form tags the attributes you can find some attributes defined in we will
go through it.
action :
Represents the URL to which this form will be submitted. This attribute is also
used to find the appropriate ActionMapping in the
Struts configuration file, which we will describe later in this section. The
value used in our example is Name, which will map to an ActionMapping
with a path attribute equal to Name.
name :Identifies the key that the ActionForm will be referenced by. We use the value NameForm. An ActionForm is an
object that is used by Struts to represent the form data as a JavaBean. It main purpose is to pass form data between View
and Controller components. We will discuss NameForm later
in this section.
type :Names the fully qualified class
name of the form bean to use in this request. For this example, we use thevalue example.NameForm, which
is an ActionForm object containing data members
matching the inputs of this form.
To
use the HTML tags, you must first add a taglib entry
in the application’s web.xml file that references the
URI /WEB-INF/struts-html.tld. This TLD describes all
of the tags in the HTML tag library. The following snippet shows the <taglib> element that must be added to the web.xml file:
|
<taglib> |
|
|
|
<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri> |
|
</taglib> |
|
The struts-html.tld is placed in the /WEB_INF
directory.
Next Step is to create the action form
The ActionForm used in this example contains a single
data member that maps directly to the name
input parameter of the form defined in the index.jsp
View. When an <html:form/>
is submitted, the Struts framework populates the matching data members of the ActionForm with the values entered into the <html:input/> tags. The Struts framework does this by
using JavaBean reflection. The accessors
of the ActionForm must follow the JavaBean
standard naming convention for example
private String name;
public void setName(String name);
public String getName();
The NameForm.java file is shown below
NameForm.java
package example;
//import statements
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
|
public
class NameForm extends ActionForm
{ |
||
|
|
private
String name = null; |
|
|
|
|
return
(name); |
|
|
} |
|
|
|
public
void setName(String name) { |
|
|
|
|
this.name = name; |
|
|
} |
|
|
|
public
void reset(ActionMapping mapping, HttpServletRequest request) { |
|
|
|
|
this.name = null; |
|
|
} |
|
|
}
|
||
To deploy the NameForm to our Struts application, you
need to compile this class, move it to the /WEB-INF/classes/example directory,
and add the following line to the <form-beans> section of the
/WEB-INF/struts-config.xml file:
<form-bean
name="nameForm" type="example.NameForm"/>
This makes the Struts application aware of the NameForm and how it should be referenced.
Now we create the out page for the sample application.
Lets name it diplayname.jsp
displayname.jsp
|
<html> |
||||
|
|
|
<table
width="80%" border="0"> |
||
|
|
|
|
<tr> |
|
|
|
|
|
|
<td>Hello <%= request.getAttribute("NAME")
%> !!</td> |
|
|
|
|
</tr> |
|
|
|
|
</table> |
||
|
</body> |
||||
Now
we move to the step two of creating the application's controller
In a Struts application, two components make up the Controller. These two
components are the org.apache.struts.action.ActionServlet and the org.apache. struts.action.Action
classes. In most Struts applications, there is one org. apache.struts.action.ActionServlet
implementation and can have many org.apache. struts.action.Action
implementations.
The org.apache.struts.action.ActionServlet
is the Controller component that handles client requests and determines which org.apache.struts.action.Action
will process the received request. When assembling simple applications, such as
the one we are building, the default ActionServlet
will satisfy your application needs, and therefore, you do not need to create a
specialized org.apache.struts.action.ActionServlet implementation.
The second component of a Struts Controller is the org.apache.struts. action.Action
class. As opposed to the ActionServlet,
the Action class must be extended for each specialized function in your
application. This class is where your application’s specific logic begins.
NameAction.java
package example;
import java.io.IOException;
import javax.servlet.ServletException;
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 NameAction extends Action { |
|||
|
|
public
ActionForward execute(ActionMapping
mapping, ActionForm form, |
||
|
|
|
String
target = new String("success"); |
|
|
|
|
|
//
Use the NameForm to get the request parameters |
|
|
|
} |
|
|
|
|
//
if no mane supplied Set the target to failure |
|
|
|
|
|
target
= new String("failure"); |
|
|
|
} |
|
|
|
|
else
{ |
|
|
|
|
|
request.setAttribute("NAME", name); |
|
|
|
} |
|
|
|
return
(mapping.findForward(target)); |
||
|
}
|
|||
Moving
to step three, to deploy the NameAction to our Struts
application, we need to compile the NameAction class
and move the class file to /WEB-INF/classes/example directory, and add the
following entry to the <action-mappings> section of the /WEB-INF/struts-config.xml file:
|
<action
path="/Name" type="example.NameAction"
name="nameForm" input="/index.jsp"> |
|
|
|
<forward
name="success" path="/displayname.jsp"/> |
|
</action>
|
|
For step four we modify the web.xml file. We have to to tell the Web application about our ActionServlet.
This is accomplished by adding the following servlet
definition to the /WEB-INF/web.xml file:
|
<servlet> |
||
|
|
<servlet-name>action</servlet-name> |
|
|
|
|
<param-name>config</param-name> |
|
|
</init-param> |
|
|
|
<load-on-startup>1</load-on-startup> |
|
|
</servlet> |
||
Once
we have told the container about the ActionServlet,
we need to tell it when the action should be executed. To do this, we have to
add a <servlet-mapping> element to the
/WEB-INF/ web.xml file:
|
<servlet-mapping> |
|
|
|
<servlet-name>action</servlet-name> |
|
</servlet-mapping> |
|
You
will notice in the previously listed index.jsp that
our action does not include a .do at the end of the URL. We do not have to
append the .do because it is automatically appended if we use the <html:form /> tag. If you do not
use the <html:form />
tag, then you will need to append .do to the action's URL. This mapping tells
the Web application that whenever a request is received with .do appended to
the URL, the servlet named action should service the
request.
Now you are ready to run the application, to begin using this application, you
need to open your Web browser to the following URL:
http://localhost:port/example/
Struts Internationalization (i18n)
Struts Internationalization (i18n) can be done with some handy modifications in
our existing application. We have to know the two Internationalization (i18n)
components that are packaged with the Struts Framework. The first of these
components, which is managed by the application Controller, is a Message class
that references a resource bundle containing Locale-dependent strings. The
second Internationalization (i18n) component is a JSP custom tag, <bean:message />, which is used
in the View layer to present the actual strings managed by the Controller.
In this section we will move with an example to understand the whole process.
We are continuing the same example which we used earlier to understand the
simple struts example in the section Struts Example.
First thing we will require for Internationalization (i18n) is a set of simple
Java properties files. Each file contains a key/value pair for each message
that you expect your application to present, in the language appropriate for
the requesting client.
This property file contains the key/value pairs for the default language of
your application. The naming format for this file is ResourceBundleName.properties.
An example of this default file, using English as the default language, would
be ApplicationResources.properties
A sample entry in this file would be app.name=Name,
this tells Struts that for every occurrence of the app.name
key the Name will be substituted.
We
must define a properties file for each language that your application will use.
This file must follow the same naming convention as the default properties
file, except that it must include the two-letter ISO language code of the
language that it represents. Example of this naming convention
For an German-speaking client would be ApplicationResources_de.properties
For an French-speaking client would be ApplicationResources_fr.properties
For an Italian-speaking client would be ApplicationResources_it.properties
For an Spanish-speaking client would be ApplicationResources_es.properties
Now add the respective entries in each properties files you require.
After you define all of the properties files for your application, you need to
make Struts aware of them. It is achieved by adding a <message-resources>
sub-element to the struts-config.xml file. Then you
should copy all the resource bundles into the application classpath,
/WEB-INF/classes/example, and then use the package path plus the base file name
as the value of the <message-resources> subelement.
The following snippet shows an example of using the <message-resources> subelement to configure a resource bundle, using the
properties files described above
<message-resources parameter="example.ApplicationResources"/>
Once this part is done we customise the view part , this is achieved throught
the second i18n component defined by the Struts Framework is a JSP custom tag,
<