Vous êtes sur la page 1sur 35

Jakarta Struts

William W. Provost

Student Guide
Revision 1.1.1

Object Innovations Course 114

Jakarta Struts

Jakarta Struts
Rev. 1.1.1

Student Guide
Information in this document is subject to change without notice. Companies, names and data
used in examples herein are fictitious unless otherwise noted. No part of this document may be
reproduced or transmitted in any form or by any means, electronic or mechanical, for any
purpose, without the express written permission of Object Innovations.
Other product and company names mentioned herein are the trademarks or registered trademarks
of their respective owners.
Copyright 2003 Object Innovations, Inc. and William W. Provost All rights reserved.
Object Innovations, Inc.
290 Turnpike Rd., Suite 413,
Westborough, MA 01581-2843
877-558-7246
www.objectinnovations.com
Printed in the United States of America.

Rev. 1.1.1

Copyright 2003-2004 Object Innovations, Inc., and William W. Provost


All Rights Reserved

ii

Jakarta Struts

Table of Contents (Overview)


Course Overview
Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6
Chapter 7
Chapter 8
Chapter 9
Chapter 10
Chapter 11

Struts Architecture
Action Mappings
Form Beans
Persistent Data
Struts Tag Libraries
The JSP Standard Tag Library
Internationalization and Localization
Validating Input
Under the Hood
Best Practices
Tiles

Appendix A

Learning Resources

Rev. 1.1.1

Copyright 2003-2004 Object Innovations, Inc., and William W. Provost


All Rights Reserved

iii

Jakarta Struts

Prerequisites
Struts is a framework for Web application
development using Java servlets and JSPs.
This course treats Struts in depth and therefore
requires students to have several skill sets coming
into the class:
HTML page authoring, at least at a basic level of fluency
Java programming, including fluent use of Java classes,
interfaces, inner classes, etc.
Java servlets programming, including interactive Web
applications, session attributes, initialization parameters,
configuration and context
JavaServer Pages (JSP) development, preferably to the
level of good familiarity with standard actions and custom
tags

Some experience with will XML is helpful in


managing Struts configuration files.
This is not absolutely critical, however.

Rev. 1.1.1

Copyright 2003-2004 Object Innovations, Inc., and William W. Provost


All Rights Reserved

iv

Jakarta Struts

Labs
The module relies on hands-on experience in various
topics and techniques.
All lab code is 100% Pure Java, written to build and
run on the J2SE SDK, version 1.4.
Students will also work with a number of file types,
all written to the applicable Java or W3C standard:
HTML pages (.html)
Java Server Pages (.jsp) and fragments
SQL scripts (.sql)
XML documents (.xml)

Rev. 1.1.1

Copyright 2003-2004 Object Innovations, Inc., and William W. Provost


All Rights Reserved

Jakarta Struts

Lab Installation
The installation files for this course have been
provided to you by your courseware vendor, training
coordinator, or instructor.
Well refer to an installation root directory, which may be a
shared network drive, or possibly the root directory of a CDROMs or floppy disk which youve been given.
Your instructor can direct you as to where to find this
material.

Assure that the J2SE SDK 1.4.1 is installed on your


system, and that its bin directory is included in your
path.
You should be able to run the following command with
substantially the same output as shown:
java version
java version "1.4.1"
...

Run the Install.bat script to install the module.


Let the script run to completion, even if you notice a few
error messages appear in console output during the install.
You can test for complete installation by checking the results
as described on the following pages.

Rev. 1.1.1

Copyright 2003-2004 Object Innovations, Inc., and William W. Provost


All Rights Reserved

vi

Jakarta Struts

Directory Structure for All Courses


The install scripts will create all the required files in
and under a standard target directory:
c:\OI for Windows systems
$HOME/OI for Linux systems

This is Object Innovations course root directory,


shared by this module along with others from the OI
curriculum.
In some cases your instructor may direct you to perform a
custom installation to some other destination.
Throughout the student guide we will use c:\OI to represent
this directory.

Rev. 1.1.1

Copyright 2003-2004 Object Innovations, Inc., and William W. Provost


All Rights Reserved

vii

Jakarta Struts

Directory Structure for the Module


Each module will install to a combination of this
shared course root and its own module root directory
c:\OI\Struts.
Under this root, the Examples directory holds code
examples, including all the starting, intermediate and answer
versions of all the labs.
The Demos directory is home to files that relate to in-class
demonstrations, many of which will lead up to further
development in labs.
The Labs directory holds one subdirectory for each lab in the
course, named for the course module and lab number. This is
where you will do the bulk of your lab work, with some
reference to code in the Examples directory.
The Docs directory holds HTML documentation giving an
overview of the courses lab and example software. The
index.html file is a good starting point for browsing the
course software, giving links to file sources, sample results,
and presentations: live XML presentations for browsers that
support it, and screenshots for browsers that dont.
Also, under each example, lab, or demo project, there will be
a Docs directory with generated javadoc for the Java code.
This can be browsed directly or can be found through the
index file mentioned above.

Rev. 1.1.1

Copyright 2003-2004 Object Innovations, Inc., and William W. Provost


All Rights Reserved

viii

Jakarta Struts

Table of Contents (Detailed)


Chapter 1: Struts Architecture........................................................................................ 1
Servlets and JSPs ............................................................................................................ 3
The Model-View-Controller Pattern............................................................................... 4
Benefits of MVC............................................................................................................. 5
MVC for Web Applications............................................................................................ 6
The Command Pattern .................................................................................................... 7
Jakarta Struts................................................................................................................... 8
Handling Requests .......................................................................................................... 9
Handling Requests Java View ................................................................................... 10
More XML, Less Java! ................................................................................................. 11
Declarations in web.xml ............................................................................................... 12
The Struts Configuration .............................................................................................. 13
Handling Requests XML View.................................................................................. 14
Example A 2-Page Web Application......................................................................... 15
JavaBeans...................................................................................................................... 18
JavaBeans in Struts ....................................................................................................... 19
Working with Forms ..................................................................................................... 20
Validation...................................................................................................................... 21
Relational Data and Other Models................................................................................ 22
Presentation Technology............................................................................................... 23
Tiles .............................................................................................................................. 24
The Tomcat Web Server ............................................................................................... 25
Starting and Stopping Tomcat ...................................................................................... 26
The Ant Build Tool....................................................................................................... 27
Course Exercises File Organization........................................................................... 28
Development Process.................................................................................................... 29
Environment and Setup................................................................................................. 30
Example Building and Deploying.............................................................................. 31
Modules ........................................................................................................................ 34
Learning Struts.............................................................................................................. 35
Designing Web Applications ........................................................................................ 36
UML.............................................................................................................................. 37
Notation ........................................................................................................................ 38
Case Study Love Is Blind .......................................................................................... 39
The Struts Application .................................................................................................. 40
Design Diagram ............................................................................................................ 41
Summary....................................................................................................................... 42
Chapter 2: Action Mappings ......................................................................................... 43
The Command Pattern for the Web .............................................................................. 45
The Action Class........................................................................................................... 46
Declaring Action Mappings.......................................................................................... 47
The <Action> Element ................................................................................................. 48
Rev. 1.1.1

Copyright 2003-2004 Object Innovations, Inc., and William W. Provost


All Rights Reserved

ix

Jakarta Struts

Example Elliptical Math ............................................................................................ 49


Example A Calculator................................................................................................ 54
The ForwardAction Class ............................................................................................. 57
Declaring a Forward ..................................................................................................... 58
Global Forwards ........................................................................................................... 59
Example Querying LoveIsBlind ................................................................................ 60
Case Study Next Steps............................................................................................... 64
More on the Love-is-Blind Domain.............................................................................. 65
Lab 2A .......................................................................................................................... 66
Other Action Subtypes.................................................................................................. 67
Declarative Exception Handling................................................................................... 68
Global Exceptions......................................................................................................... 69
Exception Handlers....................................................................................................... 70
The Standard Exception Handler.................................................................................. 71
The Periscope................................................................................................................ 72
Example Exceptions in Calculator............................................................................. 73
Example Exceptions in Ellipsoid............................................................................... 76
Lab 2B........................................................................................................................... 77
Summary....................................................................................................................... 78
Chapter 3: Form Beans .................................................................................................. 85
Working with HTML Forms......................................................................................... 87
Managing Information .................................................................................................. 88
What Not to Do............................................................................................................. 89
Form Beans ................................................................................................................... 91
The Action Form Class ................................................................................................. 92
Declaring an Action Form ............................................................................................ 93
Relationship to Input..................................................................................................... 94
Relationship to Actions................................................................................................. 95
Relationship to the Model............................................................................................. 96
Relationship to Output .................................................................................................. 97
Example Ellipsoid Form Bean................................................................................... 98
Example Dropping Exceptions ................................................................................ 100
Lab 3A ........................................................................................................................ 103
Lab 3B......................................................................................................................... 104
Declaring Form Properties.......................................................................................... 105
The DynaActionForm Class ....................................................................................... 106
Map-Backed Forms..................................................................................................... 107
Lab 3C (Optional)....................................................................................................... 108
Validation.................................................................................................................... 109
Strong Typing? ........................................................................................................... 110
Form Bean Design ...................................................................................................... 111
Coarse-Grained Action Forms .................................................................................... 112
The reset Method ........................................................................................................ 113
Summary..................................................................................................................... 114
Chapter 4: Persistent Data........................................................................................... 123
Many Models for Models ........................................................................................... 125
Rev. 1.1.1

Copyright 2003-2004 Object Innovations, Inc., and William W. Provost


All Rights Reserved

Jakarta Struts

JDBC........................................................................................................................... 126
Connection, Statement, and ResultSet........................................................................ 127
Sample Code ............................................................................................................... 128
Two Paths to a Connection ......................................................................................... 129
Many Paths to a DataSource....................................................................................... 130
The Struts DataSource Manager ................................................................................. 131
The <data-source> Element ........................................................................................ 132
MySQL ....................................................................................................................... 133
MySQL Server Setup.................................................................................................. 134
MySQL Database Setup.............................................................................................. 135
Example Web Retailing ........................................................................................... 136
Multi-Tier Architecture............................................................................................... 140
Business Logic Beans ................................................................................................. 141
Persistence Code ......................................................................................................... 142
EJB.............................................................................................................................. 143
Demo A Database for LoveIsBlind ......................................................................... 144
Lab 4 ........................................................................................................................... 149
Summary..................................................................................................................... 150
Chapter 5: Struts Tag Libraries.................................................................................. 153
Building View Components........................................................................................ 155
Struts Tag Libraries .................................................................................................... 156
Deployment of Custom Tags ...................................................................................... 157
Struts Tag Library Namespaces.................................................................................. 158
Attributes for Struts Tags............................................................................................ 159
The HTML Tag Library.............................................................................................. 160
Building Forms ........................................................................................................... 161
The <html:form> Tag ................................................................................................. 162
The <html:text> Tag, et. al. ........................................................................................ 163
Forms and Form Beans ............................................................................................... 164
Scenarios for Data Transfer ........................................................................................ 165
Scope and Duration of Form Data .............................................................................. 166
Demo LoveIsBlind Forms ....................................................................................... 167
Managing Hyperlinks ................................................................................................. 174
Example Links in the Results Page.......................................................................... 175
The <html:errors> Tag................................................................................................ 176
The Logic Tag Library................................................................................................ 177
Other Struts Tag Libraries .......................................................................................... 178
Case Study Next Steps............................................................................................. 179
Lab 5 ........................................................................................................................... 180
Summary..................................................................................................................... 181
Chapter 6: The JSP Standard Tag Library ............................................................... 187
The JSP Standard Tag Library.................................................................................... 189
The JSP Expression Language.................................................................................... 190
Using JSP Expressions................................................................................................ 191
EL Syntax ................................................................................................................... 192
JSTL Namespaces....................................................................................................... 193
Rev. 1.1.1

Copyright 2003-2004 Object Innovations, Inc., and William W. Provost


All Rights Reserved

xi

Jakarta Struts

The JSTL Core Library............................................................................................... 194


Example Odds and Evens ........................................................................................ 195
The JSTL Formatting Library..................................................................................... 197
Example Date and Time .......................................................................................... 198
The JSTL SQL Library ............................................................................................... 200
Example The Web Retailer...................................................................................... 201
The JSTL XML Library.............................................................................................. 203
Example Rental Housing ......................................................................................... 204
Mixing JSTL and Struts Tags ..................................................................................... 207
Using EL with Struts Tags.......................................................................................... 208
Case Study Next Steps............................................................................................. 209
Lab 6A ........................................................................................................................ 210
Lab 6B......................................................................................................................... 211
Summary..................................................................................................................... 212
Chapter 7: Internationalization and Localization ..................................................... 219
Such Long Words! ...................................................................................................... 221
i18n in Java ................................................................................................................. 222
Locales ........................................................................................................................ 223
Determining Locale .................................................................................................... 224
Time Zones ................................................................................................................. 225
Resource Bundles ....................................................................................................... 226
Finding a Resource Bundle......................................................................................... 227
i18n in Struts Configuration ....................................................................................... 228
i18n in Struts Actions and Forms ............................................................................... 229
i18n in Struts Tag Libraries and JSTL........................................................................ 230
Example The Calculator .......................................................................................... 231
Example The Language of Love.............................................................................. 232
i18n in Validation ....................................................................................................... 234
Lab 7 ........................................................................................................................... 235
Summary..................................................................................................................... 236
Chapter 8: Validating Input ........................................................................................ 239
We All Seek Validation .............................................................................................. 241
Where, When, and How? ............................................................................................ 242
Validation in Web Applications ................................................................................. 243
Validate and Repeat .................................................................................................... 244
Validation in Struts ..................................................................................................... 245
The Struts Validator.................................................................................................... 246
The ValidatorForm Class............................................................................................ 247
Dyna-This and Action-That ................................................................................... 248
Validating ActionForm Subtypes ............................................................................... 249
Configuring Validation ............................................................................................... 250
Validators.................................................................................................................... 251
The required Validator ............................................................................................ 252
The intRange Validator ........................................................................................... 253
Rules ........................................................................................................................... 254
Demo Validating Semi-Axis Lengths...................................................................... 255
Rev. 1.1.1

Copyright 2003-2004 Object Innovations, Inc., and William W. Provost


All Rights Reserved

xii

Jakarta Struts

Is <html:form> Necessary?......................................................................................... 259


Reporting Errors ......................................................................................................... 260
Example Highlighting Invalid Fields....................................................................... 261
Case Study Almost Home! ...................................................................................... 264
Coarse-Grained Beans and Validation........................................................................ 265
Multi-Page Validation................................................................................................. 266
Lab 8A ........................................................................................................................ 267
Client-Side Validation ................................................................................................ 268
Demo Client-Side Validation................................................................................... 269
Limitations on the Client Side .................................................................................... 270
Implementing a Validator ........................................................................................... 271
Example Positive Numbers...................................................................................... 272
Implementing validate ()............................................................................................. 274
Lab 8B (Optional)....................................................................................................... 275
Summary..................................................................................................................... 276
Chapter 9: Under the Hood ......................................................................................... 285
Digging Deeper........................................................................................................... 287
Global Objects ............................................................................................................ 288
The Globals Keys........................................................................................................ 289
Examples JSP Access to Globals............................................................................. 290
Struts Modules ............................................................................................................ 291
Struts, Servlets, and JSP ............................................................................................. 292
Know Thy Source ....................................................................................................... 293
The ActionServlet Class ............................................................................................. 294
ActionServlet Cohorts................................................................................................. 295
The RequestProcessor Class ....................................................................................... 296
The Action Class......................................................................................................... 297
Struts Configuration in Depth..................................................................................... 298
Configuring Action Mappings .................................................................................... 299
Controller Configuration............................................................................................. 300
Plug-Ins....................................................................................................................... 301
Implementing a Plug-In .............................................................................................. 302
org.apache.struts.config .............................................................................................. 303
Logging....................................................................................................................... 304
The Commons Logging API....................................................................................... 305
Severity Levels ........................................................................................................... 306
Creating a Commons Log ........................................................................................... 307
Log4J .......................................................................................................................... 308
Categories ................................................................................................................... 309
Appenders ................................................................................................................... 310
Configuration .............................................................................................................. 311
Logging Setup............................................................................................................. 312
Demo Logging Configurations ................................................................................ 313
Demo Logging in a Web Application...................................................................... 318
org.apache.struts.util ................................................................................................... 320
Commons BeanUtils ................................................................................................... 321
Rev. 1.1.1

Copyright 2003-2004 Object Innovations, Inc., and William W. Provost


All Rights Reserved

xiii

Jakarta Struts

Initializing Persistence Classes................................................................................... 322


Solutions ..................................................................................................................... 323
Lab 9A ........................................................................................................................ 324
Lab 9B......................................................................................................................... 325
Summary..................................................................................................................... 326
Chapter 10: Best Practices ........................................................................................... 333
Effective Struts Development ..................................................................................... 335
Cardinality .................................................................................................................. 336
One Form Bean to Many Anythings........................................................................... 337
One View to Many Actions ........................................................................................ 338
Many Actions to One View ........................................................................................ 339
Example Branching.................................................................................................. 340
One Action to Many Views ........................................................................................ 342
Many Mappings to One Action?................................................................................. 343
Chaining Actions ........................................................................................................ 344
Dynamic Forwarding .................................................................................................. 346
The Mediator Tier....................................................................................................... 347
Form Beans as Mediators ........................................................................................... 348
Leverage from the Business Tier ................................................................................ 349
Reflection.................................................................................................................... 350
Using BeanUtils.......................................................................................................... 351
Lab 10A ...................................................................................................................... 352
Reusing Validation Rules ........................................................................................... 353
Multipage Validation .................................................................................................. 354
Validating Immediate Inputs ...................................................................................... 355
Mapping-Based Validation ......................................................................................... 356
Graceful Validation..................................................................................................... 357
Lab 10B....................................................................................................................... 358
Summary..................................................................................................................... 359
Chapter 11: Tiles........................................................................................................... 365
Consistent Look and Feel ........................................................................................... 367
Reusable Layouts........................................................................................................ 368
Reusable Content ........................................................................................................ 369
The Tiles Framework.................................................................................................. 370
Layouts........................................................................................................................ 371
Instantiating Layouts................................................................................................... 372
Tiles ............................................................................................................................ 373
Body-Wrap Insertions................................................................................................. 374
Demo Refactoring Love is Blind ............................................................................. 375
Tiles and Stylesheets................................................................................................... 381
Attributes .................................................................................................................... 382
The Tiles Context........................................................................................................ 383
Page Inheritance.......................................................................................................... 384
Definitions .................................................................................................................. 385
Advantages of Definitions .......................................................................................... 386
Aggregation and Inheritance....................................................................................... 387
Rev. 1.1.1

Copyright 2003-2004 Object Innovations, Inc., and William W. Provost


All Rights Reserved

xiv

Jakarta Struts

The Tiles Plug-In ........................................................................................................ 388


Extending Definitions ................................................................................................. 389
Forwarding to Definitions........................................................................................... 390
Dynamic Page Description ......................................................................................... 391
Performance ................................................................................................................ 392
Lab 11 ......................................................................................................................... 393
Summary..................................................................................................................... 394
Appendix A: Learning Resources............................................................................... 397

Rev. 1.1.1

Copyright 2003-2004 Object Innovations, Inc., and William W. Provost


All Rights Reserved

xv

Jakarta Struts

Chapter 7

Chapter 7
Internationalization and
Localization

Rev. 1.1

Copyright 2003 Object Innovations, Inc., and William W. Provost


All Rights Reserved

219

Jakarta Struts

Chapter 7

Internationalization and Localization


Objectives
After completing this unit you will be able to:
Describe the Java 2 Standard Edition framework for
internationalization and localization.
Explain how Struts builds on this framework:
Configuration of resource bundles as defaults, or under
simple key names, in the application context.
Consistent use of message keys, instead of literal values,
throughout the Struts tag libraries.

Use internationalization features in your Struts


applications:
Define user-visible strings in resource bundles.
Provide user feedback based on message keys.
Use Struts and Java standard tag libraries to present
completely localized user interfaces.

Rev. 1.1

Copyright 2003 Object Innovations, Inc., and William W. Provost


All Rights Reserved

220

Jakarta Struts

Chapter 7

Such Long Words!


The unwieldy terms internationalization and
localization refer to the development effort required
to make a piece of software usable in multiple
countries and locales.
This means managing multiple written languages, and in
the this chapter well look at how to create locale-specific
resource bundles that can be swapped in based on the users
or applications chosen locale.
It also involves formatting output according to local
conventions, even where language is not an issue per se.
Although we will not study it in detail, the JSTL formatting
tag library provides excellent support for this.

To save ink and breath, many developers eventually


find their way to the term i18n an extremely terse
phrase which is perhaps an overcompensation.
There are 18 letters between the first and last letters of the
word internationalization.

Rev. 1.1

Copyright 2003 Object Innovations, Inc., and William W. Provost


All Rights Reserved

221

Jakarta Struts

Chapter 7

i18n in Java
The J2SE provides complete support for
internationalization, although the APIs are not the
most facile things in the world.
The framework is based on a handful of classes in the
java.util package:
Locale
TimeZone
ResourceBundle

Well consider each of these briefly, although for


Struts purposes it will be resource bundles that are
the most interesting.

Rev. 1.1

Copyright 2003 Object Innovations, Inc., and William W. Provost


All Rights Reserved

222

Jakarta Struts

Chapter 7

Locales
In order to produce output that will make the most
sense to a human user, an application first needs to
understand a few things about that users locale:
The language he or she reads and writes. This will influence
the language used in application messages and output.
The place from which he or she is using the application. This
will affect the format in which certain output is produced.
The time zone from which he or she is using the application.
This will affect date and time values, rather than formats.

Java software uses the java.util.Locale class to


encapsulate the first two factors.
This class can produce and parse a string representation that
combines two-letter codes for language and country.
Both of these code sets are standardized by the ISO see
ISO-639 and ISO-3166, respectively.
The resulting string representation is of the form xx-XX,
where xx is the lowercase language code and XX is the
uppercase country code.
For example, this chapter was written in en-US.

Rev. 1.1

Copyright 2003 Object Innovations, Inc., and William W. Provost


All Rights Reserved

223

Jakarta Struts

Chapter 7

Determining Locale
The application can set its locale preference.
This is typically in response to some user input perhaps a
configuration performed once when a user creates a profile.
This may also be done purely for testing purposes.

Much more likely for Web applications is that the


locale will be provided by the browser or other user
agent.
Popular browsers will rely on the operating system to provide
locale information, and will provide that locale to the
application per request.
They also have preferences screens that allow the user to
choose another locale or language in which he or she would
prefer to interact with Web applications.
In this way, applications that dont set a locale at all can be
assured that locale-dependent behaviors will be tailored
correctly for the current user.

Rev. 1.1

Copyright 2003 Object Innovations, Inc., and William W. Provost


All Rights Reserved

224

Jakarta Struts

Chapter 7

Time Zones
Java software uses the java.util.TimeZone class to
encapsulate information about a time zone.
Again, there is a common string representation as well, in
this case specified as part of the Java standard platform.
Two formats are possible: a terse one stating GMT plus or
minus some number of hours, and a verbose one in which the
names of places are written longhand and separated by
slashes, as in America/Los_Angeles.

As with locales, the prevailing time zone can be set by


application code, but it is much more common to get
it from the client side.

Rev. 1.1

Copyright 2003 Object Innovations, Inc., and William W. Provost


All Rights Reserved

225

Jakarta Struts

Chapter 7

Resource Bundles
A resource bundle is a collection of named resources
dedicated to a specific locale.
An application will commonly deploy several resource
bundles, one for each locale or language supported for
example separate bundles for US English, UK English,
French and Spanish.
Each such bundle will have the same set of keys, but
different values for those keys.
The application relies on lookups into these bundles to
present a locale-specific interface from the same Java code.

The java.util.ResourceBundle class encapsulates a


resource bundle as loaded into memory.
Keys are always strings, but values can be of any Java type,
including primitives and objects.

More conveniently, bundles of message strings can be


implemented in properties files that simply list the
strings in name=value format, one per text line.
This is still backed by a Java class, actually, which is
java.util.PropertyResourceBundle.

In either case, the placement of the artifact is


significant: the Java package and class name, or the
subdirectory path and name of a properties file, will
be used to identify it as a bundle for a certain
purpose.
Rev. 1.1

Copyright 2003 Object Innovations, Inc., and William W. Provost


All Rights Reserved

226

Jakarta Struts

Chapter 7

Finding a Resource Bundle


When a Java class or JSP requests a localized
resource such as a message string, it does so by
providing:
The message key
The bundles base name
The desired locale (or it relies on the prevailing default)

Resource-management code in the J2SE runtime


resolves this request by finding the correct resource
bundle.
The base name combined with the locale gives the name of a
concrete bundle, and the runtime searches for a bundle of this
calculated name.
The actual algorithm is a good bit more complex, allowing
for more or less specific locale suffices to be used in bundle
names. (For instance a bundle might be dedicated to a
language only, and not to a locale.)
Also, an ordered list of preferred locales may be supplied by
a browser, rather than a single default locale.
We will not delve into all the tricks and twists of i18n
resource management and deployment in this chapter.

Rev. 1.1

Copyright 2003 Object Innovations, Inc., and William W. Provost


All Rights Reserved

227

Jakarta Struts

Chapter 7

i18n in Struts Configuration


The Struts framework further simplifies the
deployment of message resources.
Resource bundles are deployed within the application
in the standard manner.
As with just about everything else in Struts, the Struts
features are built on existing standards, without hiding or
compromising those standards.
Application code can still use the usual J2SE i18n APIs.

Message bundles can be declared in the


configuration, using top level elements of type
<message-resources>.
These elements map bundles by a key name into the
application context. The key can be omitted to declare a
default resource bundle.
The parameter attribute connects this key (or default) to a
resource bundle by the usual Java i18n base name.

This does nothing of real value for the applications


Java code, but it puts message bundles into objects
that can be easily discovered and read by tag
libraries.
Both Struts and Java standard tag libraries can use bundles
published in this way Struts implicitly, JSTL explicitly.

Rev. 1.1

Copyright 2003 Object Innovations, Inc., and William W. Provost


All Rights Reserved

228

Jakarta Struts

Chapter 7

i18n in Struts Actions and Forms


Controller code is of course not responsible for
presenting localized messages.
It is often required to produce those messages,
however.
With i18n thoroughly supported in Struts through
presentation tags, in generic actions and other
components, and in the Struts Validator application
code can speak entirely in terms of message keys.
When reporting an error, it is a key thats passed to the global
ERRORS object.
The same is true for placing a general-purpose message in the
MESSAGES object.

Rev. 1.1

Copyright 2003 Object Innovations, Inc., and William W. Provost


All Rights Reserved

229

Jakarta Struts

Chapter 7

i18n in Struts Tag Libraries and JSTL


The Struts tag libraries support internationalization
everywhere that a literal message might be produced
to the output stream.
HTML tags can use message keys for captions, titles, and
alternate text. For convenience, most tags offer pairs of
attributes, such as title (literal) and titleKey (resource key to
be dereferenced), only one of which will be used.
The tag <bean:message> provides a simple and direct
means of producing a message of a certain key.
Throughout, the default resource bundle (localized according
to client preference, if possible) is used, or can be overridden
by a separate attribute (the attribute name varies).

JSTL provides the formatting library, which offers


several tags dedicated to localized processing:
Date, time, number and currency formatting.
Production of localized messages.
<fmt:message> does more or less the same job as
<bean:message>, although again the Struts tag is a step
easier to use because it assumes the use of the Struts default
resource bundle, where the JSTL tag would need it to be
declared in a separate attribute or separate
<fmt:setBundle> tag.

Rev. 1.1

Copyright 2003 Object Innovations, Inc., and William W. Provost


All Rights Reserved

230

Jakarta Struts

Chapter 7

Example The Calculator


Weve seen a few examples of localized strings
already although at runtime only a default resource
bundle is deployed.
One such example is the Calculator application,
which reports exceptional conditions using the
application-defined error.serverException key.
See Examples\Calculator\Step3:
Config\struts-config.xml:
<global-exceptions>
<exception
type="java.lang.Exception"
handler="oi.math.Handler"
key="error.serverException"
/>
</global-exceptions>

Config\classes\application.properties:
error.serverException=<p>An error was encountered
in processing this request. The calculator memory
has been cleared; you can try again!</p>

View\Calculator.jsp:
<b style="color:red" ><html:errors /></b>

Rev. 1.1

Copyright 2003 Object Innovations, Inc., and William W. Provost


All Rights Reserved

231

Jakarta Struts

Chapter 7

Example The Language of Love


A more ambitious example of internationalizing an
application is found in Examples\Amour.
This is a variant of an earlier version of Love is Blind
in which the initial walk-in query is presented
entirely using resource strings.
The JSPs use the JSTL formatting tags, bypassing the Struts
configuration to look up the resource bundle by the standard
J2SE algorithm.
<%@ taglib prefix="fmt"
uri="http://java.sun.com/jstl/fmt_rt" %>
<fmt:setBundle var="strings"
basename="oi.LoveIsBlindStrings" />

The rest of the page presentation is carefully resourced:


<center><h2>
<fmt:message key="Title" bundle="${strings}" />
&#8212; <fmt:message key="SubtitleQuery"
bundle="${strings}" /></h2></center>
<p>
<fmt:message key="Prompt" bundle="${strings}" />
</p>
<form action="Query.do"><center><table
cellpadding=4 border=0>
<tr>
<td><fmt:message key="Sex"
bundle="${strings}" />:</td>
...

English- and French-language resource bundles have


been deployed.
Rev. 1.1

Copyright 2003 Object Innovations, Inc., and William W. Provost


All Rights Reserved

232

Jakarta Struts

Chapter 7

Example The Language of Love


Build and test the application it should look normal
at first.
Try setting a preference in your browser for the
locale fr-FR and then reload the query page

Rev. 1.1

Copyright 2003 Object Innovations, Inc., and William W. Provost


All Rights Reserved

233

Jakarta Struts

Chapter 7

i18n in Validation
In the next chapter well take a long look at the Struts
Validator.
It is here that internationalization first imposes itself
upon many Struts developers.
Validation rules and the validator framework in general are
mostly about generically handling problems.
This means declaring messages that should be handed back to
the user when problems arise.
Message keys are the natural way to do this, and Struts
philosophy on internationalization seems to be, In for a
penny, in for a pound.
So, where in other aspects of development one might choose
to forego internationalization for early iterations, when it
comes to validation there is really no other way to go about it
(except to build ones own validator).

Rev. 1.1

Copyright 2003 Object Innovations, Inc., and William W. Provost


All Rights Reserved

234

Jakarta Struts

Chapter 7

Lab 7
An Authentication Error Message
In this lab you will enhance the existing Love is Blind logon page.
It currently does nothing to inform the user when authentication
fails it is just shown repeatedly until the user gets it right or goes
away. You will add code to Logon.jsp to present an advisory
message, and a key and value to the default resource bundle to
support the JSP.
Detailed instructions are contained in the Lab 7 write-up at the end
of the chapter.
Suggested time: 30-45 minutes.

Rev. 1.1

Copyright 2003 Object Innovations, Inc., and William W. Provost


All Rights Reserved

235

Jakarta Struts

Chapter 7

Summary
On the other hand, Struts thoroughness with, and
insistence on, internationalization can be helpful.
The use of a default resource bundle, and the
consistent use of message keys throughout the system,
makes it fairly simple to get internationalization
support involved in the very first iteration of a Struts
application.
Many applications really never will grow to use
anything but their default bundles, but they will be
none the worse for having gotten into the system.
Bear in mind that even if an application never needs to be
internationalized in the strictest sense, there can still be
advantages to having a string table in play.
Certain presentations button captions, phrasing of user
messages, etc. can be fine-tuned late in the development
process without difficulty, if message keys are used
consistently in the application.

Those that do need to support multiple languages and


locales can start to add new bundles.
One great thing about the Java i18n framework is that once
the base names and keys for bundles and strings are known
and in use, the simple act of adding a resource bundle to the
WAR file will activate resources for the new target language.
No additional configuration of any sort is required.

Rev. 1.1

Copyright 2003 Object Innovations, Inc., and William W. Provost


All Rights Reserved

236

Jakarta Struts

Chapter 7

Lab 7
An Authentication Error Message
Introduction
In this lab you will enhance the existing Love is Blind logon page. It currently does
nothing to inform the user when authentication fails it is just shown repeatedly until the
user gets it right or goes away. You will add code to Logon.jsp to present an advisory
message, and a key and value to the default resource bundle to support the JSP.
Suggested Time: 30-45 minutes.
Root Directory:

OI\Struts

Directories:

Labs\Lab7
Examples\LoveIsBlind\Step7
Examples\LoveIsBlind\Step8

Files:

View\Member\Logon.jsp
Config\classes\application.properties

(do your work here)


(backup copy of starter files)
(contains lab solution)

Instructions
1. Build and test the starter application. As you may already have noticed, if you flunk
your logon, the JSP just shows again, with password cleared. Its a pretty good guess
whats happening, from the users perspective, but its hardly good presentation.
2. Review the code in oi\LIB\action\Authenticate.java, and note that on failure it sets a
request-scope attribute authenticated to false.
3. Open Logon.jsp and add code right after the page heading. Start by using <c:if>
with a test attribute of ${authenticated == false} to see if authentication failed on
the recent request.
4. Inside the conditional tag, create a <b></b> element, and inside it a <fmt:bundle>
with attribute baseName set to application. Tags occurring inside this one will
default to look up keys in the application.properties bundle already deployed with
the application.
5. Finally, inside the bundle tag, add a <fmt:message> tag with key equal to
error.invalidLogon. This is a new key for the application, which will need to have
a value defined.

Rev. 1.1

Copyright 2003 Object Innovations, Inc., and William W. Provost


All Rights Reserved

237

Jakarta Struts

Chapter 7

6. Open application.properties and define a message for the new key something to
the effect that the user and password couldnt be authenticated in the member
database.
7. Build and retest the application, and provide a bad password for someone. You
should see your message clearly in the re-displayed logon page. (This is the Step8
answer code; the remaining steps are a quick experiment and are not reflected
anywhere in the example steps.)
Optional Steps
8. Try the same thing with <bean:message>, as follows.
9. You will need to declare the Struts bean tag library instead of the JSTL formatting
library.
10. You will still need the <c:if> conditional, but then you can place a <bean:message>
tag with the same key attribute where the <fmt:message> is currently.
11. You can remove the <fmt:bundle> entirely, since the new tag will automatically
look up the Struts default bundle as already configured.

Rev. 1.1

Copyright 2003 Object Innovations, Inc., and William W. Provost


All Rights Reserved

238

Vous aimerez peut-être aussi