You are on page 1of 89

Introduction to Struts

Framework

Agenda

Overview of JSP Model 1 Architecture.


Model-View-Controller (MVC) Architecture.
What is Struts?
Struts Components
Objectives
Model Components
View Components
Struts Tag Libraries
Application Resource File
Error Handling
Exception Handling
Validator Framework
Tiles Framework

STRUTS

JSP Model 1
Architecture

JSP Model 1 Architecture


Model 1 architecture is the easiest way of
developing JSP based web application.
The core part of Model 1 architecture is JSP
and JavaBeans.
Here, the client request is sent directly to the
JSP page.
The JSP contains embedded code and tags
to access the JavaBeans.
The JavaBeans holds the HTTP request
parameters from the query string and
connects to the middle tier or directly to the
database for additional processing.
The JSP page selects the next page for the
client.
No extra servlet involved in the process.

Model 2 (MVC)
Architecture

MVC Design Pattern


The MVC pattern separates responsibilities into three layers of
functionality:
Model: The data and business logic
View: The presentation
Controller: The flow control

Each of these layers is loosely coupled to provide maximum


flexibility with minimum effect on the other layers.

MVC - Model
In the MVC design pattern, the Model provides access to the
necessary business data as well as the business logic needed to
manipulate that data.
The Model typically has some means to interact with persistent
storage such as a database to retrieve, add, and update the
data.
The Model can be built up with Simple Java Beans or EJB or
WebServices

MVC - Controller
The Controller handles all requests from the user and selects the view to
return.
When the Controller receives a request, the Controller forwards the request to
the appropriate handler, which interprets what action to take based on the
request.
The Controller calls on the Model to perform the desired function.
After the Model has performed the function, the Controller selects the View to
send back to the user based on the state of the Models data.

MVC - View
The View is responsible for displaying data from the Model to the
user.
This layer also sends user data to the Controller.
In the case of a Web application, this means that both the request
and the response are in the domain of the View.

In Model2 a controller, implemented as Servlet, is introduced to handle the user


requests.
In Model2 the user request is processed in the following steps after submission

Model2
(MVC) Architecture
1. Controller Servlet handles the users request.

2. Controller Servlet then instantiates appropriate Java Beans based on the


request parameters.
3. Java Beans communicates to the middle tier or directly to the database to
fetch the required data.
4. Controller then sets the resultant JavaBeans (same or new) in either,
request, session or application context.
5. Controller then dispatches the request to the next view based on the
request URL.
6. The View uses the resultant Java Beans to display data.

10

Model2 (MVC) Architecture


2. Access Model &
<<Controller>> invoke Business Logic
1. Request

Servlet
4. Get result &
set in scope

<<Model>>
Datastore

Browser

JavaBeans
5. Dispatch to
next view

6. Response

Session EJB etc.

Uses
<<View>>
JSP

1.
11

J2EE Application Server

3. Connect to
Database &
get/save data

Advantages of MVC
Greater flexibility:
Its easy to add different View types (HTML, XML) and interchange
varying data stores of the Model because of the clear separation of
layers in the pattern.
Best use of different skill sets:
Designers can work on the View, programmers more familiar with data
access can work on the Model, and others skilled in application
development can work on the Controller. Differentiation of work is
easier to accomplish because the layers are distinct.
Ease of maintenance:
The structure and flow of the application are clearly defined, making
them easier to understand and modify. Parts are loosely coupled with
each other.

12

What is Struts

13

Struts

advantages

Struts is an open source created by Craig McClanahan


& then donated to the Jakarta project of the Apache
Software Foundation (ASF) in 2000 . In June 2001 struts
1.0 was released
The Struts framework is a rich collection of Java
libraries and can be broken down into the following
major pieces
- Base framework
- Jsp tag libraries
- Tiles plugin
- Validator plugin

14

MVC pattern as enforced in Struts


Struts provides a concrete implementation of the Controller part of
the pattern.
It also provides the connections between the Controller and Model
layers and between the Controller and View layers,
It doesnt insist on any particular View paradigm or does not requires
the Model to be constructed in a particular way.
Some of the components of Struts are
ActionServlet : The primary Controller class
Action :: The handler class
ActionForm :: Holds the data of the user request
struts-config.xml :: configuration file

15

MVC pattern as enforced in Struts

16

STRUTS

A Framework

3. Invoke
reset and
validate

Action
Servlet

1. HTTP
Request

2. Read
mappings
Struts-config.xml

17

Action
Form

4. Return
Errors
5. Invoke execute method
6. Return forward action
7. Forward to
appropriate View
Presentation
(JSP)

Action
Class

Struts
Components

18

ActionServlet
The central component of the Struts Controller is the
ActionServlet.
ActionServlet performs two important things
On startup it reads the Struts Configuration file and loads it into
memory in the init() method.
In doGet() or doPost() methods it intercepts HTTP request and
handles the appropriately.

The web.xml of the application should have ActionServlet


declared using <servlet></servlet>, along with appropriate
servlet mappings using <servlet-mapping></servletmapping>.

19

A sample web.xml entry for ActionServlet


<servlet>
<servlet-name>action</servlet-name>
<servletclass>org.apache.struts.action.ActionServlet</servlet
-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</paramvalue>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Standard Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
20

RequestProcessor
After ActionServlet has intercepted the HTTP request, it delegates
the request handling to RequestProcessor.
The process() of the RequestProcessor does the following :
The RequestProcessor first retreives the ActionMappings
from struts-config.xml.
From ActionMappings it gets the name of ActionForm and
populates it if it is already created otherwise creates it first.
Next if some validations are required on the input, that is done
Lastly the execute() method of Action class is invoked.
The RequestProcessor is specified in struts-config.xml as
<controller processorClass =
"org.apache.struts.action.RequestProcessor"/>

21

ActionMappings as shown in struts-config.xml


<!-- ====================Form Bean Definitions -->
<form-beans>
<form-bean
name="NameForm"
type="app1.NameForm"/>
</form-beans>
<!-- =============== Action Mapping Definitions -->
<action-mappings>
<action
path="/NameSubmit"
type="app1.NameAction"
name="NameForm"
scope="request"
validate="true"
input="/Name2.jsp">
<forward name="success" path = "/Success.jsp" />
<forward name="failure" path ="Failure.jsp" />
</action>
</action-mappings>
22

ActionForm
ActionForm is essentially a JavaBean with a list of private
attributes and a pair of getXXX() and setXXX() method for each
of the attributes.
Struts application extends the ActionForm class to implement its
own.
RequestProcessor instantiates the ActionForms subclass and
puts it in appropriate scope.
Next RequestProcessor iterates through the HTTP request
parameters and populates the matching attributes.
Next if validation is enabled the validate() method is called.

23

ActionForm class

public class NameForm extends ActionForm{


private String firstName;
private String lastName;
public String getFirstName(){
return firstName;
}
public String getLastName() {
return lastName;
}
public void setFirstName(String fName){
firstName=fName;
}
public void setLastName(String lName){
lastName=lName;
}
}

24

STRUTS

25

ActionForm Lifecycle

Action
The RequestProcessor instantiates the Action class specified in the
ActionMapping and invokes the execute() method.
The signature of execute() is

public ActionForward execute (ActionMapping mapping,


ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
The execute() method should preferably contain only the
presentation logic and no business logic.
Putting business logic in execute() method limits the reuse of the
business logic, which is not a very good design.
This is an ideal starting point in the web layer to invoke the business logic.

26

Action (contd)
We should have our own class which extends the Action class
public class NameAction extends Action {
public ActionForward execute (ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception{
NameForm nform = (NameForm) form;
System.out.println(In NameAction ::execute());
return mapping.findForward("success");
}
}

27

ActionForward
ActionForward is the class that encapsulates the next view information.
ActionForward encapsulates the association of the logical name and
the physical JSP page.
The logical name and physical page is specified in the strutsconfig.xml file.
<forward name="success" path = "/Success.jsp" />
After successful execution the execute() method of Acton class returns
the appropriate ActionForward.
return mapping.findForward("success");
The ActionForward can be either local to one ActionMapping or
global.

28

struts-config.xml
struts-config.xml is the primary configuration file for the
Controller.
Five important sections in struts-config.xml are:
1.
2.
3.
4.
5.

29

Form bean definition section


Global forward definition section [optional]
Action mapping definition section
Controller configuration section [optional]
Application Resources definition section.
[optional]

struts-config.xml
Form bean definition section
The form bean definition section contains one or more entries
for each ActionForm.
Each form bean is identified by an unique logical name.
Type is the fully qualified class name of the ActionForm.
<form-beans>
<form-bean name="NameForm
type="app1.NameForm"/>
</form-beans>

30

struts-config.xml

Action mapping definition section


The ActionMapping section contains the mapping from URL path to an
Action class and also associates a Form bean with the path.
The attributes and elements of ActionMapping are:

Attribute/Element
Path
Type
Name
Scope
Validate
Input
Forward

31

Description
The URL path
The Action class name.
The logical name of the Form
bean
Scope of the Form bean
If true the form bean is validated
The page to which the control will be
forwarded in case of an error.
The physical page/another ActionMapping
to which the control should be forwarded
when ActionForward with this name is
selected in the execute method of the
Action class.

<?xml version="1.0" encoding="ISO-8859-1" ?>


<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
<struts-config>
<form-beans>
<form-bean

name="NameForm

type="app1.NameForm"/>

</form-beans>
<action-mappings>
<action
path="/NameSubmit"
type="app1.NameAction"
name="NameForm"
scope="request"
validate="true"
input="/Name2.jsp">
<forward name="success" path = "/Success.jsp" />
<forward name="failure" path ="Failure.jsp" />
</action>
</action-mappings>
</struts-config>
32

struts-config.xml
Global forward definition section
Unlike, local forwards Global Forward section is
accessible from any ActionMapping.
<global-forwards>
<forward name=logon path=/logon.jsp/>
</global-forwards>

33

Model
Components

34

STRUTS Model Components


Business Logic Beans
Should encapsulate the functional logic of your
application as method calls on JavaBeans
designed for this purpose
For small to medium sized applications, business
logic beans might be ordinary JavaBeans that
interact with system state beans passed as
arguments, or ordinary JavaBeans that access a
database using JDBC calls
For larger applications, these beans will often be
stateful or stateless Enterprise JavaBeans (EJBs )
35

View
Components

36

STRUTS

View Components

Struts framework does not provide JSPs.


It provides JSP Custom Tag libraries which can be used in JSPs.
<%@ page language = "java" %>
<html>
<body>
<!-- <form action = "NameSubmit.do"> -->
<form name="NameForm" method="post" action="/App1/NameSubmit.do">
First Name
<input type = "text" name ="fName" >
<BR>
Second Name
<input type = "text" name ="lName" >
<BR>
<input type = "SUBMIT" >
</form></body></html>

37

STRUTS Tag
Libraries

38

STRUTS

Tag Libraries

HTML Tags Used to generate HTML forms that


interact with the Struts APIs
Bean Tags Used to work with Java bean objects
in JSPs , such as accessing bean values .
Logic Tags Used to cleanly implement simple
conditional logic in JSPs

39

HTML
<html:html></html:html>
The tags Tags
in the Struts HTML library form a bridge
between a JSP view and the other components of a Web
application.

Consequently, the majority of the HTML tags involve HTML forms.


<html:html>.</html:html>
The JSP file should inlcude the TLD files for this::
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
The web.xml should inlcude
<taglib>
<taglib-uri>/WEB-INF/struts-bean</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-html</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>

40

HTML tags

<html:base/>

<html:base/> allows the usage of relative URL instead of abosolute


URLs.
The page context root is declared with the <html:base/> tag.
An sample would be like
<head>
<html:base/>
</head>
Now all URLs not starting with / are assumed to be relative to the
base href.

41

HTML Tags

<html:form></html:form>

<html:form> tag generates the HTML representation of the Form.


It has one mandatory attribute action.
The action attribute represents the ActionMapping for this form.
A sample
<html:form action="/NameSubmit">

</html:form>

It reads the ActionMapping in strust-config.xml and generates an HTML


equivalent as
<form name="NameForm" method="post"
action="/App1/NameSubmit.do"> </form>

42

HTML tags

<html:text/>,<html:submit>

<html:text/> tag generates the HTML representation of the text box.


It has one mandatory attribute called property.
The value of the property should exactly match with the attribute
name specified in the Formbean.
<html:text property="firstName" />
<html:submit> generates equivalent code for the submit button in
HTML>

43

HTML Tags Typical HTML Form


<HTML><BODY>
<FORM><TABLE WIDTH="100%">
<TR><TD>First Name</TD>
<TD><INPUT TYPE="TEXT" NAME="Name" SIZE="40" MAXLENGTH="40"></TD></TR>
<TR><TD>Street Address</TD>
<TD><INPUT TYPE="TEXT" NAME="Address" SIZE="40" MAXLENGTH="40"></TD></TR>
</TABLE>
</FORM></BODY>
44

</HTML>

<HTML:HTML>
<BODY>
<HTML:FORM action="/CustomerForm >
<TABLE WIDTH="100%">
<TD><html:text property="name" size="40" maxlength="40" /></TD></TR>
<TD>< html:text property="address" size ="40" maxlength ="40" /></TD></TR>
<TD>< html:text property="city" size ="20" maxlength ="20" /></TD></TR>
</TABLE>
</HTML:FORM>
</BODY>
45

HTML Tags Typical Struts Form

</HTML:HTML>

Bean Tags
Tag Name

Description

cookie
Define a scripting variable based on the value(s) of the specified request cookie.
define
Define a scripting variable based on the value(s) of the specified bean property.
header
Define a scripting variable based on the value(s) of the specified request header.
include
Load the response from a dynamic application request and make it available as a bean.
message
Render an internationalized message string to the response.
page
Expose a specified item from the page context as a bean.
parameter
Define a scripting variable based on the value(s) of the specified request parameter.
resource
Load a web application resource and make it available as a bean.
size
Define a bean containing the number of elements in a Collection or Map.
struts
46

Expose a named Struts internal configuration object as a bean.


write

Logic Tags

The Logic tag library contains tags that are useful in


managing conditional generation of output text, looping
over object collections for repetitive generation of output
text, and application flow management.

47

Logic Tags
Tag Name

Description

empty
equal
forward
greaterEqual
greaterThan
iterate
lessEqual
lessThan
match
messagesNotPresent
messagesPresent
notEmpty
notEqual
notMatch
notPresent
present
48

redirect

Evaluate the nested body content of this tag if the requested variable is either null or an empty string.
Evaluate the nested body content of this tag if the requested variable is equal to the specified value.
Forward control to the page specified by the specified ActionForward entry.
Evaluate the nested body content of this tag if requested variable is greater than or equal to specified value.
Evaluate the nested body content of this tag if the requested variable is greater than the specified value.
Repeat the nested body content of this tag over a specified collection.
Evaluate the nested body content of this tag if requested variable is greater than or equal to specified value.
Evaluate the nested body content of this tag if the requested variable is less than the specified value.
Evaluate the nested body content of this tag if specified value is an appropriate substring of requested
variable.
Generate the nested body content of this tag if the specified message is not present in this request.
Generate the nested body content of this tag if the specified message is present in this request.
Evaluate the nested body content of this tag if the requested variable is neither null nor an empty string.
Evaluate the nested body content of this tag if the requested variable is not equal to the specified value.
Evaluate the nested body content of tag if specified value not an appropriate substring of requested variable.
Generate the nested body content of this tag if the specified value is not present in this request.
Generate the nested body content of this tag if the specified value is present in this request.

Logic Tags - Example


<html:form action="/ImageLocationForm" >
<TABLE border="1">
<TR>
<TH width="94">Emp Id</TH>
<TH width="98">First Name</TH>
</TR>
<logic:iterate id="det" name="empDetail" property="empDetail" >
<tr>
<td><bean:write name="det" property="empId"/>
<td><bean:write name="det" property="empFirstName"/>
</tr>
</logic:iterate>
49

</TABLE>

STRUTS View Components


Building Forms with Struts
The taglib directive tells the JSP page compiler
where to find the tag library descriptor for the
Struts tag library
The errors tag displays any error messages
that have been stored by a business logic
component, or nothing if no errors have been
stored

50

STRUTS

View Components

Building Forms with Struts continued


The form tag renders an HTML <form> element, based
on the specified attributes
The form tag also associates all of the fields within this
form with a request scoped FormBean that is stored
under the key FormName
The form bean can also be specified in the Struts
configuration file, in which case the Name and Type can
be omitted here
The text tag renders an HTML <input> element of type
"text
The submit and reset tags generate the corresponding
buttons at the bottom of the form

51

STRUTS

View Components

Input field types supported


checkboxes
hidden fields
password input fields
radio buttons
reset buttons
select lists
options
submit buttons
text input fields
textareas
52

STRUTS

View Components

Useful Presentation Tags


[logic] iterate repeats its tag body once for each element
of a specified collection (which can be an
Enumeration, a Hashtable, a Vector, or an array of
objects)
[logic] present depending on which attribute is specified,
this tag checks the current request, and evaluates the
nested body content of this tag only if the specified
value is present
[logic] notPresent the companion tag to present,
notPresent provides the same functionality when the
specified attribute is not present
53

STRUTS View Components


Automatic Form Validation
Struts offers an additional facility to validate the
input fields it has received
To utilize this feature, override the validate()
method in your ActionForm class
The validate() method is called by the controller
servlet after the bean properties have been
populated, but before the corresponding action
class's perform() method is invoked

54

Application
Resource File

55

Application Resource File


The Application Resource File stores the pre-defined messages to
be shown in the JSP pages.
Application Resource files normally has an extension as .properties
and are stored in /WEB-INF/classes/
It also needs to be declared in the struts-config.xml as
<message-resources parameter="app1.App1Messages" />
Where, app1 is the respective package name and
App1Messages.properties is the file name.

56

ApplicationResources.properties
prompt.firstName = First Name
prompt.lastName = Last Name
button.save = Save Me
button.cancel = Cancel Me
errors.header=<h3><font color="red">Validation
Error</font></h3>
Plz rectify the following error:<ul>
errors.footer=</ul><hr>
error.firstName.null = First Name is required

57

Modified JSP file


<html:form action="/NameSubmit">
<bean:message key = "prompt.firstName"/>
<html:text property="firstName" />
<br>
<bean:message key = "prompt.lastName"/>
<html:text property="lastName" />
<br>
<html:submit>
<bean:message key = "button.save" />
</html:submit>
</html:form>
58

Handling Errors

59

validate() method in ActionForm


Struts provides validate() method in the ActionForm to deal with
input validations.
The validate() method gets populated just after the Form bean is
populated.
A sample validate() method looks like
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request){ ..}
If errors are found then the validate() method returns ActionErrors
object which holds the error.
The generated erros are rendered in the JSP page using the
<html:errors/> tag.

60

validate() method
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request){
ActionErrors errors = new ActionErrors();
if(firstName == null || firstName.trim().equals(""))
{
errors.add("firstName",new
ActionError("error.firstName.null"));
}
return errors;
}

61

Exception Handling

62

STRUTS Exception Handling


Struts supports two types of Exception
Handling
Declarative
Programmatic

63

STRUTS Exception Handling


Declarative exception handling
An application's exception-handling policies,
including which exceptions are thrown and how
they are to be handled, are maintained in a
separate file (typically using XML)
The XML file is completely external to the
application code
This approach makes it easier to modify the
exception-handling logic without major
recompilation of the code.

64

STRUTS Exception Handling


Sample Struts configuration file for declarative
exception handling
<struts-config>
<action-mappings>
<action path="/search
type="com.jamesholemes.minihr.SearchAction"
name=searchForm"
scope="request"
input="/search.jsp">

65

STRUTS

Exception Handling

<exception
key=error.NoResultsFoundException"
path="/exception.jsp"
handler=com.oreily.struts.ExceptionHandler
type=com.jamesholmes.minihr.NoResultsFoundException"/>
</action>
</action-mappings>
</struts-config>

66

STRUTS

Exception Handling

Sequence of Events
The RequestProcessor class executes its
processException() method.
Finds the Exception in the action mapping
The default exception handler creates and stores an
ActionError into the specified scope and gives the control
to the resource specified in the path attribute

67

STRUTS

Exception Handling

Programmatic Exception Handling


Application specific exception handling in the code.
Helps logging the Exception.
Programmatically create and store ActionError into
the appropriate scope and forward control to the
appropriate ActionForward.

68

STRUTS

Exception Handling

Sample code of Action Class handling Exception.


try{
// do something
}catch (Exception exp) {
//log the exception
//Create and store the ActionError
ActionErrors errs = new ActionErrors();

69

STRUTS

Exception Handling

ActionError newEr = new


ActionError(exp.getErrorCode(),exp.getArgs());
errs.add(ActionErrors.GLOBAL_ERROR,newEr);
saveErrors(request, errs);

70

//Return an ActionForward for the failure resource.


return mapping.findForward(failure);

Validator Framework

71

STRUTS

Validator Framework

Need for a Validation Framework


Validator Framework allows you to move all the
validation logic completely outside of the ActionForm.
Declaratively configure all the validations for an
application through external XML files.
No validation logic is necessary in the ActionForm,
which makes your application easier to develop and
maintain.
It provides many standard built-in validations
72

STRUTS

Validator Framework

Required jar files under WEB-INF/lib


Commons-validator.jar
Jakarta-oro.jar

Two important config files


Validation-rules.xml
Validation.xml
73

STRUTS

Validator Framework

Validation-rules.xml
<validator
name=required
classname="org.apache.struts.util.StrutsValidator"
method=validateRequired
methodParams=java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionErrors,
javax.servlet.http.HttpServletRequest
msg="errors.required">
</validator>

74

STRUTS

Validator Framework

The Validator element supports seven attributes


name
classname
method
methodParams
msg
depends

75

STRUTS

Validator Framework

The resource bundle should have the following default key-value pairs.
errors.required={0} is required.
errors.minlength={0} cannot be less than {1} characters.
errors.maxlength={0} cannot be greater than {1} characters.
errors.invalid={0} is invalid.
errors.byte={0} must be a byte.
errors.short={0} must be a short.
errors.integer={0} must be an integer.
errors.long={0} must be a long.
errors.float={0} must be a float.
errors.double={0} must be a double.
errors.date={0} is not a date.
errors.range={0} is not in the range {1} through {2}.
errors.creditcard={0} is not a valid credit card number.
errors.email={0} is an invalid email address

76

STRUTS

Validator Framework

Validation.xml
This file is application specific
It defines which validation rules from the validationrules.xml are used by a particular ActionForm
The validation logic is associated with one or more
ActionForm classes through this external file.

77

STRUTS Validator Framework


A sample validation.xml file
<form-validation>
<global>
<constant>
<constant-name>phone</constant-name>
<constant-value>^\(?(\d{3})\)?[-| ]?(\d{3})[-| ]?(\d{4})$</constantvalue>
</constant>
</global>

78

STRUTS

Validator Framework

<formset>
<form name="checkoutForm">
<field property="phone depends="required,mask">
<arg0 key="registrationForm.firstname.displayname"/>
<var>
<var-name>mask</var-name>
<var-value>${phone}</var-value>
</var>
</field>
</form>
</formset>
</form-validation>
79

STRUTS

Validator Framework

Using an ActionForm with the Validator


The standard ActionForm cannot be used in the validator
framework.
Use subclass of the ActionForm class that is specifically
designed to work with the Validator framework
Use DynaValidatorForm or ValidatorForm

80

STRUTS

Validator Framework

Steps to use default Validator framework- A Summary


Put validation-rules.xml and validation.xml files under WEB-INF
Edit validation.xml file according to the need
Put the default key-value pairs in the application resource
bundle file.
Use DynaValidatorForm or ValidatorForm instead of the default
ActionForm

81

The Tiles Framework

82

STRUTS

The Tiles Framework

Each tile is just a web page in its own right & theyll all be inserted where you
want them.
This model promotes reusability.
If the only thing that changes between the 500 web pages on your site is the
individuals pages body and you want to keep the header, footer and a navigation
menu the same for each page , Tiles can help you a lot
Header

Menu

Body

Footer

83

Sample code for to implement Tiles Framework


<tiles:insert page=Layout.jsp flush=true>
<tiles:put name=title value=Using Tiles/>
<tiles:put name=header value=header.jsp/>
<tiles:put name=footer value=footer.jsp/>
<tiles:put name=menu value=menu.jsp/>
<tiles:put name=body value=body.jsp />
</tiles:insert>

84

Need to plug in tiles-definitions.xml in struts-config.xml file


<struts-config>
.
.
<plug-in className=org.apache.struts.tiles.TilesPlugin>
<set-property property=definitions-config value=/WEB-INF/tilesdefinitions.xml/>
.
.
</struts-config>

85

Creating the Layout


<% taglib uri=/WEB-INF/struts-tiles.tld
prefix=tiles%>
<html>
<head>
<title><tiles:getAsString name=title/>
</title>
</head>
<table width=100%>
<tr>
<td colsspan=2>
<tilese:insert attribute=header/>
</td>
</tr>
< tr>
<td width=80>
<tiles:insert attribute=menu/>
</td>
<td>
<tiles:insert attribute=body />
</td>
</tr>
<tr>
<td colspan=2 >
<tiles:insert attribute=footer/>
</td>
</tr>
</table>
</body>
</html>
86

Struts

Resources

Struts Main Web Site


http://struts.apache.org/index

Struts Book
Struts Essential Skills Steven Holzner
Struts Complete Reference James Holmes , Schildt
Struts User Guide
http://jakarta.apache.org/struts/userGuide/index.html

Various Struts Resources


http://jakarta.apache.org/struts/resources.html

87

Questions

88

89

You might also like