weboi - student guide struts

Upload: anonymous-ruqy8qme

Post on 06-Jul-2018

213 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/17/2019 Weboi - Student Guide Struts

    1/35

     

    Object Innovations Course 114

    William W. Provost

    Student Guide Revision 1.1.1

    Jakarta Struts

  • 8/17/2019 Weboi - Student Guide Struts

    2/35

    Jakarta Struts

    Rev. 1.1.1 Copyright © 2003-2004 Object Innovations, Inc., and William W. Provost iiAll Rights Reserved

    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-7246www.objectinnovations.com

    Printed in the United States of America.

  • 8/17/2019 Weboi - Student Guide Struts

    3/35

    Jakarta Struts

    Rev. 1.1.1 Copyright © 2003-2004 Object Innovations, Inc., and William W. Provost iiiAll Rights Reserved

    Table of Contents (Overview) 

    Course Overview

    Chapter 1 Struts Architecture

    Chapter 2 Action Mappings

    Chapter 3 Form Beans

    Chapter 4 Persistent Data

    Chapter 5 Struts Tag Libraries

    Chapter 6 The JSP Standard Tag Library

    Chapter 7 Internationalization and Localization

    Chapter 8 Validating Input

    Chapter 9 Under the Hood

    Chapter 10 Best Practices

    Chapter 11 Tiles

    Appendix A Learning Resources

  • 8/17/2019 Weboi - Student Guide Struts

    4/35

    Jakarta Struts

    Rev. 1.1.1 Copyright © 2003-2004 Object Innovations, Inc., and William W. Provost ivAll Rights Reserved

    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.

  • 8/17/2019 Weboi - Student Guide Struts

    5/35

    Jakarta Struts

    Rev. 1.1.1 Copyright © 2003-2004 Object Innovations, Inc., and William W. Provost vAll Rights Reserved

    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)

  • 8/17/2019 Weboi - Student Guide Struts

    6/35

    Jakarta Struts

    Rev. 1.1.1 Copyright © 2003-2004 Object Innovations, Inc., and William W. Provost viAll Rights Reserved

    Lab Installation

    • The installation files for this course have been

    provided to you by your courseware vendor, training

    coordinator, or instructor.

    − We’ll refer to an installation root directory, which may be a

    shared network drive, or possibly the root directory of a CD-

    ROMs or floppy disk which you’ve 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 –versionjava 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 resultsas described on the following pages.

  • 8/17/2019 Weboi - Student Guide Struts

    7/35

    Jakarta Struts

    Rev. 1.1.1 Copyright © 2003-2004 Object Innovations, Inc., and William W. Provost viiAll Rights Reserved

    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.

  • 8/17/2019 Weboi - Student Guide Struts

    8/35

    Jakarta Struts

    Rev. 1.1.1 Copyright © 2003-2004 Object Innovations, Inc., and William W. Provost viiiAll Rights Reserved

    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 furtherdevelopment 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 course’s lab and example software. Theindex.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 don’t.

    − 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.

  • 8/17/2019 Weboi - Student Guide Struts

    9/35

    Jakarta Struts

    Rev. 1.1.1 Copyright © 2003-2004 Object Innovations, Inc., and William W. Provost ixAll Rights Reserved

    Table of Contents (Detailed)

    Chapter 1: Struts Architecture........................................................................................ 1

    Servlets and JSPs ............................................................................................................ 3The Model-View-Controller Pattern............................................................................... 4

    Benefits of MVC............................................................................................................. 5

    MVC for Web Applications............................................................................................ 6The Command Pattern .................................................................................................... 7

    Jakarta Struts................................................................................................................... 8

    Handling Requests .......................................................................................................... 9Handling Requests – Java View ................................................................................... 10

    More XML, Less Java!................................................................................................. 11

    Declarations in web.xml ............................................................................................... 12The Struts Configuration .............................................................................................. 13

    Handling Requests – XML View.................................................................................. 14Example – A 2-Page Web Application......................................................................... 15JavaBeans...................................................................................................................... 18

    JavaBeans in Struts ....................................................................................................... 19

    Working with Forms..................................................................................................... 20

    Validation...................................................................................................................... 21Relational Data and Other Models................................................................................ 22

    Presentation Technology............................................................................................... 23

    Tiles .............................................................................................................................. 24The Tomcat Web Server............................................................................................... 25

    Starting and Stopping Tomcat ...................................................................................... 26

    The Ant Build Tool....................................................................................................... 27Course Exercises – File Organization........................................................................... 28

    Development Process.................................................................................................... 29Environment and Setup................................................................................................. 30

    Example – Building and Deploying.............................................................................. 31

    Modules ........................................................................................................................ 34Learning Struts.............................................................................................................. 35

    Designing Web Applications........................................................................................ 36

    UML.............................................................................................................................. 37

     Notation ........................................................................................................................ 38Case Study – Love Is Blind .......................................................................................... 39

    The Struts Application.................................................................................................. 40Design Diagram ............................................................................................................ 41Summary....................................................................................................................... 42

    Chapter 2: Action Mappings ......................................................................................... 43

    The Command Pattern for the Web.............................................................................. 45

    The Action Class........................................................................................................... 46Declaring Action Mappings.......................................................................................... 47

    The Element ................................................................................................. 48

  • 8/17/2019 Weboi - Student Guide Struts

    10/35

    Jakarta Struts

    Rev. 1.1.1 Copyright © 2003-2004 Object Innovations, Inc., and William W. Provost xAll Rights Reserved

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

    Example – A Calculator................................................................................................ 54The ForwardAction Class ............................................................................................. 57

    Declaring a Forward ..................................................................................................... 58

    Global Forwards ........................................................................................................... 59

    Example – Querying LoveIsBlind................................................................................ 60Case Study – Next Steps............................................................................................... 64

    More on the Love-is-Blind Domain.............................................................................. 65

    Lab 2A .......................................................................................................................... 66Other Action Subtypes.................................................................................................. 67

    Declarative Exception Handling................................................................................... 68

    Global Exceptions......................................................................................................... 69Exception Handlers....................................................................................................... 70

    The Standard Exception Handler.................................................................................. 71

    The Periscope................................................................................................................ 72Example – Exceptions in Calculator............................................................................. 73

    Example – Exceptions in Ellipsoid............................................................................... 76Lab 2B........................................................................................................................... 77

    Summary....................................................................................................................... 78

    Chapter 3: Form Beans .................................................................................................. 85

    Working with HTML Forms......................................................................................... 87

    Managing Information .................................................................................................. 88

    What Not to Do............................................................................................................. 89Form Beans ................................................................................................................... 91

    The Action Form Class................................................................................................. 92

    Declaring an Action Form ............................................................................................ 93Relationship to Input..................................................................................................... 94

    Relationship to Actions................................................................................................. 95Relationship to the Model............................................................................................. 96

    Relationship to Output.................................................................................................. 97

    Example – Ellipsoid Form Bean................................................................................... 98Example – Dropping Exceptions ................................................................................ 100

    Lab 3A ........................................................................................................................ 103

    Lab 3B......................................................................................................................... 104Declaring Form Properties.......................................................................................... 105

    The DynaActionForm Class ....................................................................................... 106

    Map-Backed Forms..................................................................................................... 107

    Lab 3C (Optional)....................................................................................................... 108

    Validation.................................................................................................................... 109Strong Typing? ........................................................................................................... 110

    Form Bean Design ...................................................................................................... 111Coarse-Grained Action Forms .................................................................................... 112

    The reset Method ........................................................................................................ 113

    Summary..................................................................................................................... 114

    Chapter 4: Persistent Data........................................................................................... 123

    Many Models for Models ........................................................................................... 125

  • 8/17/2019 Weboi - Student Guide Struts

    11/35

    Jakarta Struts

    Rev. 1.1.1 Copyright © 2003-2004 Object Innovations, Inc., and William W. Provost xiAll Rights Reserved

    JDBC........................................................................................................................... 126

    Connection, Statement, and ResultSet........................................................................ 127Sample Code ............................................................................................................... 128

    Two Paths to a Connection ......................................................................................... 129

    Many Paths to a DataSource....................................................................................... 130

    The Struts DataSource Manager................................................................................. 131The Element........................................................................................ 132

    MySQL ....................................................................................................................... 133

    MySQL Server Setup.................................................................................................. 134MySQL Database Setup.............................................................................................. 135

    Example – Web Retailing........................................................................................... 136

    Multi-Tier Architecture............................................................................................... 140Business Logic Beans ................................................................................................. 141

    Persistence Code ......................................................................................................... 142

    EJB.............................................................................................................................. 143Demo – A Database for LoveIsBlind ......................................................................... 144

    Lab 4 ........................................................................................................................... 149Summary..................................................................................................................... 150

    Chapter 5: Struts Tag Libraries.................................................................................. 153

    Building View Components........................................................................................ 155

    Struts Tag Libraries .................................................................................................... 156

    Deployment of Custom Tags...................................................................................... 157

    Struts Tag Library Namespaces.................................................................................. 158Attributes for Struts Tags............................................................................................ 159

    The HTML Tag Library.............................................................................................. 160

    Building Forms ........................................................................................................... 161The Tag ................................................................................................. 162

    The Tag, et. al. ........................................................................................ 163Forms and Form Beans............................................................................................... 164

    Scenarios for Data Transfer ........................................................................................ 165

    Scope and Duration of Form Data .............................................................................. 166Demo – LoveIsBlind Forms ....................................................................................... 167

    Managing Hyperlinks ................................................................................................. 174

    Example – Links in the Results Page.......................................................................... 175The Tag................................................................................................ 176

    The Logic Tag Library................................................................................................ 177

    Other Struts Tag Libraries .......................................................................................... 178

    Case Study – Next Steps............................................................................................. 179

    Lab 5 ........................................................................................................................... 180Summary..................................................................................................................... 181

    Chapter 6: The JSP Standard Tag Library ............................................................... 187

    The JSP Standard Tag Library.................................................................................... 189The JSP Expression Language.................................................................................... 190

    Using JSP Expressions................................................................................................ 191

    EL Syntax ................................................................................................................... 192JSTL Namespaces....................................................................................................... 193

  • 8/17/2019 Weboi - Student Guide Struts

    12/35

    Jakarta Struts

    Rev. 1.1.1 Copyright © 2003-2004 Object Innovations, Inc., and William W. Provost xiiAll Rights Reserved

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

    Example – Odds and Evens ........................................................................................ 195The JSTL Formatting Library..................................................................................... 197

    Example – Date and Time .......................................................................................... 198

    The JSTL SQL Library............................................................................................... 200

    Example – The Web Retailer...................................................................................... 201The JSTL XML Library.............................................................................................. 203

    Example – Rental Housing ......................................................................................... 204

    Mixing JSTL and Struts Tags ..................................................................................... 207Using EL with Struts Tags.......................................................................................... 208

    Case Study – Next Steps............................................................................................. 209

    Lab 6A ........................................................................................................................ 210Lab 6B......................................................................................................................... 211

    Summary..................................................................................................................... 212

    Chapter 7: Internationalization and Localization ..................................................... 219

    Such Long Words! ...................................................................................................... 221

    i18n in Java ................................................................................................................. 222Locales........................................................................................................................ 223

    Determining Locale .................................................................................................... 224Time Zones ................................................................................................................. 225

    Resource Bundles ....................................................................................................... 226

    Finding a Resource Bundle......................................................................................... 227

    i18n in Struts Configuration ....................................................................................... 228i18n in Struts Actions and Forms ............................................................................... 229

    i18n in Struts Tag Libraries and JSTL........................................................................ 230

    Example – The Calculator .......................................................................................... 231Example – The Language of Love.............................................................................. 232

    i18n in Validation ....................................................................................................... 234Lab 7 ........................................................................................................................... 235

    Summary..................................................................................................................... 236

    Chapter 8: Validating Input ........................................................................................ 239

    We All Seek Validation .............................................................................................. 241Where, When, and How?............................................................................................ 242

    Validation in Web Applications ................................................................................. 243

    Validate and Repeat .................................................................................................... 244Validation in Struts ..................................................................................................... 245

    The Struts Validator.................................................................................................... 246

    The ValidatorForm Class............................................................................................ 247

    Dyna-This and Action-That …................................................................................... 248Validating ActionForm Subtypes ............................................................................... 249

    Configuring Validation............................................................................................... 250

    Validators.................................................................................................................... 251The “required” Validator ............................................................................................ 252

    The “intRange” Validator ........................................................................................... 253

    Rules ........................................................................................................................... 254Demo – Validating Semi-Axis Lengths...................................................................... 255

  • 8/17/2019 Weboi - Student Guide Struts

    13/35

    Jakarta Struts

    Rev. 1.1.1 Copyright © 2003-2004 Object Innovations, Inc., and William W. Provost xiiiAll Rights Reserved

    Is Necessary?......................................................................................... 259

    Reporting Errors ......................................................................................................... 260Example – Highlighting Invalid Fields....................................................................... 261

    Case Study – Almost Home! ...................................................................................... 264

    Coarse-Grained Beans and Validation........................................................................ 265

    Multi-Page Validation................................................................................................. 266Lab 8A ........................................................................................................................ 267

    Client-Side Validation ................................................................................................ 268

    Demo – Client-Side Validation................................................................................... 269Limitations on the Client Side .................................................................................... 270

    Implementing a Validator ........................................................................................... 271

    Example – Positive Numbers...................................................................................... 272Implementing validate ()............................................................................................. 274

    Lab 8B (Optional)....................................................................................................... 275

    Summary..................................................................................................................... 276

    Chapter 9: Under the Hood ......................................................................................... 285

    Digging Deeper........................................................................................................... 287Global Objects ............................................................................................................ 288

    The Globals Keys........................................................................................................ 289Examples – JSP Access to Globals............................................................................. 290

    Struts Modules ............................................................................................................ 291

    Struts, Servlets, and JSP ............................................................................................. 292

    Know Thy Source ....................................................................................................... 293The ActionServlet Class ............................................................................................. 294

    ActionServlet Cohorts................................................................................................. 295

    The RequestProcessor Class ....................................................................................... 296The Action Class......................................................................................................... 297

    Struts Configuration in Depth..................................................................................... 298Configuring Action Mappings.................................................................................... 299

    Controller Configuration............................................................................................. 300

    Plug-Ins....................................................................................................................... 301Implementing a Plug-In .............................................................................................. 302

    org.apache.struts.config .............................................................................................. 303

    Logging....................................................................................................................... 304The Commons Logging API....................................................................................... 305

    Severity Levels ........................................................................................................... 306

    Creating a Commons Log........................................................................................... 307

    Log4J .......................................................................................................................... 308

    Categories ................................................................................................................... 309Appenders ................................................................................................................... 310

    Configuration .............................................................................................................. 311Logging Setup............................................................................................................. 312

    Demo – Logging Configurations ................................................................................ 313

    Demo – Logging in a Web Application...................................................................... 318org.apache.struts.util................................................................................................... 320

    Commons BeanUtils ................................................................................................... 321

  • 8/17/2019 Weboi - Student Guide Struts

    14/35

    Jakarta Struts

    Rev. 1.1.1 Copyright © 2003-2004 Object Innovations, Inc., and William W. Provost xivAll Rights Reserved

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

    Solutions ..................................................................................................................... 323Lab 9A ........................................................................................................................ 324

    Lab 9B......................................................................................................................... 325

    Summary..................................................................................................................... 326

    Chapter 10: Best Practices........................................................................................... 333Effective Struts Development..................................................................................... 335

    Cardinality .................................................................................................................. 336

    One Form Bean to Many Anythings........................................................................... 337One View to Many Actions ........................................................................................ 338

    Many Actions to One View ........................................................................................ 339

    Example – Branching.................................................................................................. 340

    One Action to Many Views ........................................................................................ 342Many Mappings to One Action?................................................................................. 343

    Chaining Actions ........................................................................................................ 344

    Dynamic Forwarding .................................................................................................. 346

    The Mediator Tier....................................................................................................... 347Form Beans as Mediators ........................................................................................... 348

    Leverage from the Business Tier ................................................................................ 349Reflection.................................................................................................................... 350

    Using BeanUtils.......................................................................................................... 351

    Lab 10A ...................................................................................................................... 352

    Reusing Validation Rules ........................................................................................... 353Multipage Validation .................................................................................................. 354

    Validating Immediate Inputs ...................................................................................... 355

    Mapping-Based Validation ......................................................................................... 356Graceful Validation..................................................................................................... 357

    Lab 10B....................................................................................................................... 358Summary..................................................................................................................... 359

    Chapter 11: Tiles........................................................................................................... 365

    Consistent Look and Feel ........................................................................................... 367

    Reusable Layouts........................................................................................................ 368Reusable Content ........................................................................................................ 369

    The Tiles Framework.................................................................................................. 370

    Layouts........................................................................................................................ 371Instantiating Layouts................................................................................................... 372

    Tiles ............................................................................................................................ 373

    Body-Wrap Insertions................................................................................................. 374

    Demo – Refactoring Love is Blind............................................................................. 375Tiles and Stylesheets................................................................................................... 381

    Attributes .................................................................................................................... 382

    The Tiles Context........................................................................................................ 383Page Inheritance.......................................................................................................... 384

    Definitions .................................................................................................................. 385

    Advantages of Definitions .......................................................................................... 386Aggregation and Inheritance....................................................................................... 387

  • 8/17/2019 Weboi - Student Guide Struts

    15/35

    Jakarta Struts

    Rev. 1.1.1 Copyright © 2003-2004 Object Innovations, Inc., and William W. Provost xvAll Rights Reserved

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

    Extending Definitions................................................................................................. 389Forwarding to Definitions........................................................................................... 390

    Dynamic Page Description ......................................................................................... 391

    Performance ................................................................................................................ 392

    Lab 11 ......................................................................................................................... 393Summary..................................................................................................................... 394

    Appendix A: Learning Resources............................................................................... 397

  • 8/17/2019 Weboi - Student Guide Struts

    16/35

    Jakarta Struts Chapter 7

    Rev. 1.1 Copyright © 2003 Object Innovations, Inc., and William W. Provost 219All Rights Reserved

    Chapter 7

    Internationalization and

    Localization

  • 8/17/2019 Weboi - Student Guide Struts

    17/35

    Jakarta Struts Chapter 7

    Rev. 1.1 Copyright © 2003 Object Innovations, Inc., and William W. Provost 220All Rights Reserved

    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 undersimple 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 presentcompletely localized user interfaces.

  • 8/17/2019 Weboi - Student Guide Struts

    18/35

    Jakarta Struts Chapter 7

    Rev. 1.1 Copyright © 2003 Object Innovations, Inc., and William W. Provost 221All Rights Reserved

    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 inthe this chapter we’ll look at how to create locale-specificresource bundles that can be swapped in based on the user’sor application’s chosen locale.

    − It also involves formatting output according to localconventions, even where language is not an issue per se.Although we will not study it in detail, the JSTL formattingtag 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.’

  • 8/17/2019 Weboi - Student Guide Struts

    19/35

    Jakarta Struts Chapter 7

    Rev. 1.1 Copyright © 2003 Object Innovations, Inc., and William W. Provost 222All Rights Reserved

    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 

    • We’ll consider each of these briefly, although for

    Struts purposes it will be resource bundles that are

    the most interesting.

  • 8/17/2019 Weboi - Student Guide Struts

    20/35

    Jakarta Struts Chapter 7

    Rev. 1.1 Copyright © 2003 Object Innovations, Inc., and William W. Provost 223All Rights Reserved

    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 user’s locale:

    − The language he or she reads and writes. This will influencethe language used in application messages and output.

    − The place from which he or she is using the application. Thiswill 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 thatcombines two-letter codes for language and country.

    − Both of these code sets are standardized by the ISO – seeISO-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 theuppercase country code.

    − For example, this chapter was written in “en-US”.

  • 8/17/2019 Weboi - Student Guide Struts

    21/35

    Jakarta Struts Chapter 7

    Rev. 1.1 Copyright © 2003 Object Innovations, Inc., and William W. Provost 224All Rights Reserved

    Determining Locale

    • The application can set its locale preference.

    − This is typically in response to some user input – perhaps aconfiguration 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 theapplication per request.

    − They also have preferences screens that allow the user tochoose another locale or language in which he or she would

     prefer to interact with Web applications.

    − In this way, applications that don’t set a locale at all can beassured that locale-dependent behaviors will be tailoredcorrectly for the current user.

  • 8/17/2019 Weboi - Student Guide Struts

    22/35

    Jakarta Struts Chapter 7

    Rev. 1.1 Copyright © 2003 Object Innovations, Inc., and William W. Provost 225All Rights Reserved

    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, inthis case specified as part of the Java standard platform.

    − Two formats are possible: a terse one stating “GMT” plus orminus some number of hours, and a verbose one in which thenames 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.

  • 8/17/2019 Weboi - Student Guide Struts

    23/35

    Jakarta Struts Chapter 7

    Rev. 1.1 Copyright © 2003 Object Innovations, Inc., and William W. Provost 226All Rights Reserved

    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 – forexample 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 issignificant: 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.

  • 8/17/2019 Weboi - Student Guide Struts

    24/35

    Jakarta Struts Chapter 7

    Rev. 1.1 Copyright © 2003 Object Innovations, Inc., and William W. Provost 227All Rights Reserved

    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 bundle’s base name 

    − The desired locale (or it relies on the prevailing default)

    • Resource-management code in the J2SE runtimeresolves this request by finding the correct resource

    bundle.

    − The base name combined with the locale gives the name of aconcrete bundle, and the runtime searches for a bundle of thiscalculated name.

    The actual algorithm is a good bit more complex, allowingfor more or less specific locale suffices to be used in bundlenames. (For instance a bundle might be dedicated to alanguage only, and not to a locale.)

    − Also, an ordered list of preferred locales may be supplied bya 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.

  • 8/17/2019 Weboi - Student Guide Struts

    25/35

    Jakarta Struts Chapter 7

    Rev. 1.1 Copyright © 2003 Object Innovations, Inc., and William W. Provost 228All Rights Reserved

    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 Strutsfeatures are built on existing standards, without hiding orcompromising 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

      .

    − These elements map bundles by a key name into theapplication context. The key can be omitted to declare a

    default resource bundle.

    − The parameter attribute connects this key (or default) to aresource bundle by the usual Java i18n base name.

    • This does nothing of real value for the application’s

    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.

  • 8/17/2019 Weboi - Student Guide Struts

    26/35

    Jakarta Struts Chapter 7

    Rev. 1.1 Copyright © 2003 Object Innovations, Inc., and William W. Provost 229All Rights Reserved

    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 that’s passed to the globalERRORS object.

    − The same is true for placing a general-purpose message in theMESSAGES object.

  • 8/17/2019 Weboi - Student Guide Struts

    27/35

    Jakarta Struts Chapter 7

    Rev. 1.1 Copyright © 2003 Object Innovations, Inc., and William W. Provost 230All Rights Reserved

    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, andalternate text. For convenience, most tags offer pairs ofattributes, such as title (literal) and titleKey (resource key to

     be dereferenced), only one of which will be used.

    The tag   provides a simple and directmeans of producing a message of a certain key.

    − Throughout, the default resource bundle (localized accordingto 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.

    −   does more or less the same job as

      , although again the Struts tag is a step

    easier to use because it assumes the use of the Struts defaultresource bundle, where the JSTL tag would need it to be

    declared in a separate attribute or separate   tag.

  • 8/17/2019 Weboi - Student Guide Struts

    28/35

    Jakarta Struts Chapter 7

    Rev. 1.1 Copyright © 2003 Object Innovations, Inc., and William W. Provost 231All Rights Reserved

    Example – The Calculator

    • We’ve 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:

    − Config\classes\application.properties:

    error.serverException=

    An error was encounteredin processing this request. The calculator memoryhas been cleared; you can try again!

    − View\Calculator.jsp:

  • 8/17/2019 Weboi - Student Guide Struts

    29/35

    Jakarta Struts Chapter 7

    Rev. 1.1 Copyright © 2003 Object Innovations, Inc., and William W. Provost 232All Rights Reserved

    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 Strutsconfiguration to look up the resource bundle by the standard

    J2SE algorithm.

    − The rest of the page presentation is carefully resourced:

     —  

     

      :...

    • English- and French-language resource bundles have

    been deployed.

  • 8/17/2019 Weboi - Student Guide Struts

    30/35

    Jakarta Struts Chapter 7

    Rev. 1.1 Copyright © 2003 Object Innovations, Inc., and William W. Provost 233All Rights Reserved

    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 …

  • 8/17/2019 Weboi - Student Guide Struts

    31/35

    Jakarta Struts Chapter 7

    Rev. 1.1 Copyright © 2003 Object Innovations, Inc., and William W. Provost 234All Rights Reserved

    i18n in Validation

    • In the next chapter we’ll 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 aremostly about generically handling problems.

    This means declaring messages that should be handed back tothe 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 chooseto forego internationalization for early iterations, when it

    comes to validation there is really no other way to go about it(except to build one’s own validator).

  • 8/17/2019 Weboi - Student Guide Struts

    32/35

    Jakarta Struts Chapter 7

    Rev. 1.1 Copyright © 2003 Object Innovations, Inc., and William W. Provost 235All Rights Reserved

    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 authenticationfails – it is just shown repeatedly until the user gets it right or goesaway. You will add code to Logon.jsp to present an advisorymessage, and a key and value to the default resource bundle tosupport the JSP.

    Detailed instructions are contained in the Lab 7 write-up at the endof the chapter.

    Suggested time: 30-45 minutes.

  • 8/17/2019 Weboi - Student Guide Struts

    33/35

    Jakarta Struts Chapter 7

    Rev. 1.1 Copyright © 2003 Object Innovations, Inc., and William W. Provost 236All Rights Reserved

    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 beinternationalized in the strictest sense, there can still beadvantages to having a string table in play.

    Certain presentations – button captions, phrasing of usermessages, etc. – can be fine-tuned late in the development

     process without difficulty, if message keys are usedconsistently 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 knownand in use, the simple act of adding a resource bundle to theWAR file will activate resources for the new target language.

    −  No additional configuration of any sort is required.

  • 8/17/2019 Weboi - Student Guide Struts

    34/35

    Jakarta Struts Chapter 7

    Rev. 1.1 Copyright © 2003 Object Innovations, Inc., and William W. Provost 237All Rights Reserved

    Lab 7

    An Authentication Error Message

    Introduction

    In this lab you will enhance the existing Love is Blind logon page. It currently doesnothing to inform the user when authentication fails – it is just shown repeatedly until theuser gets it right or goes away. You will add code to Logon.jsp to present an advisorymessage, 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 (do your work here)Examples\LoveIsBlind\Step7 (backup copy of starter files)Examples\LoveIsBlind\Step8 (contains lab solution)

    Files: View\Member\Logon.jsp

    Config\classes\application.properties

    Instructions

    1. Build and test the starter application. As you may already have noticed, if you flunkyour logon, the JSP just shows again, with password cleared. It’s a pretty good guesswhat’s happening, from the user’s perspective, but it’s hardly good presentation.

    2. Review the code in oi\LIB\action\Authenticate.java , and note that on failure it sets arequest-scope attribute “authenticated” to “false”.

    3. Open Logon.jsp and add code right after the page heading. Start by using  with a test attribute of “${authenticated == ‘false’}” to see if authentication failed onthe recent request.

    4. Inside the conditional tag, create a  element, and inside it a  with attribute baseName set to “application”. Tags occurring inside this one willdefault to look up keys in the application.properties  bundle already deployed with

    the application.

    5. Finally, inside the bundle tag, add a  tag with key equal to“error.invalidLogon”. This is a new key for the application, which will need to havea value defined.

  • 8/17/2019 Weboi - Student Guide Struts

    35/35

    Jakarta Struts Chapter 7

    6. Open application.properties  and define a message for the new key – something tothe effect that the user and password couldn’t be authenticated in the memberdatabase.

    7. Build and retest the application, and provide a bad password for someone. Youshould 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 reflectedanywhere in the example steps.)

    Optional Steps

    8. Try the same thing with , as follows.

    9. You will need to declare the Struts bean tag library instead of the JSTL formattinglibrary.

    10. You will still need the  conditional, but then you can place a  

    tag with the same key attribute where the  is currently.

    11. You can remove the  entirely, since the new tag will automaticallylook up the Struts default bundle as already configured.