57
Struts Student Workbook

Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Embed Size (px)

Citation preview

Page 1: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Student Workbook

Page 2: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Page ii Rev 1.3.2 © 2011 ITCourseware, LLC

Struts

Struts

Suzanne Werle

Published by ITCourseware, LLC., 7245 South Havana Street, Suite 100, Centennial, CO 80112

Contributing Author: Jamie Romero

Editor: Rick Sussenbach

Special thanks to: Many instructors whose ideas and careful review have contributed to the qualityof this workbook, including Brandon Caldwell, John Crabtree, Julie Johnson, and Mike Naseef, andthe many students who have offered comments, suggestions, criticisms, and insights.

Copyright © 2011 by ITCourseware, LLC. All rights reserved. No part of this book may be reproducedor utilized in any form or by any means, electronic or mechanical, including photo-copying, recording, or byan information storage retrieval system, without permission in writing from the publisher. Inquiries should beaddressed to ITCourseware, LLC., 7245 South Havana Street, Suite 100, Centennial, Colorado, 80112.(303) 302-5280.

All brand names, product names, trademarks, and registered trademarks are the property of their respectiveowners.

Page 3: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

© 2011 ITCourseware, LLC Rev 1.3.2 Page iii

Struts

Contents

Chapter 1 - Course Introduction ............................................................................................................... 7

Course Objectives .............................................................................................................................. 8Course Overview .............................................................................................................................. 10Using the Workbook ......................................................................................................................... 11Suggested References ....................................................................................................................... 12

Chapter 2 - Struts Overview ................................................................................................................... 15

What is Struts? .................................................................................................................................. 16Model 1 Design Pattern .................................................................................................................... 18Model 2 / MVC Design Pattern ........................................................................................................ 20Implementing MVC with a Framework ............................................................................................. 22The Struts Framework ...................................................................................................................... 24Basic Struts Components .................................................................................................................. 26Basic Struts Components (cont'd) ..................................................................................................... 28Struts Documentation ........................................................................................................................ 30A Struts-Based Application: Logon .................................................................................................. 32Labs ................................................................................................................................................. 34

Chapter 3 - Struts in a Simple Web Application ....................................................................................... 37

Stars Information Application ............................................................................................................ 38List Stars Flow .................................................................................................................................. 40Display Star Flow ............................................................................................................................. 42ActionServlet: the Controller ............................................................................................................ 44struts-config.xml ................................................................................................................................ 46ActionForm: Form State .................................................................................................................. 48The execute Method of StarsListAction............................................................................................. 50The execute Method of StarsDisplayAction ....................................................................................... 52Directing Processing Flow with an ActionForward............................................................................. 54Building a View with Tags .................................................................................................................. 56Review: Flow through a Typical Struts-Based Application ................................................................ 58Labs ................................................................................................................................................. 60

Page 4: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Page iv Rev 1.3.2 © 2011 ITCourseware, LLC

Struts

Chapter 4 - The Controller ...................................................................................................................... 63

ActionServlet as a Controller ............................................................................................................. 64RequestProcessor ............................................................................................................................. 66Developer Responsibilities ................................................................................................................. 68Mapping ........................................................................................................................................... 70Forwards .......................................................................................................................................... 72Lifecycle of an ActionForm ............................................................................................................... 74ActionForm Considerations ............................................................................................................... 76The reset Method.............................................................................................................................. 78The validate Method ......................................................................................................................... 80Labs ................................................................................................................................................. 82

Chapter 5 - Action and the Business Model ............................................................................................. 85

The execute Method of Action .......................................................................................................... 86execute() Method Considerations ...................................................................................................... 88Handling an Error .............................................................................................................................. 90Threading Considerations .................................................................................................................. 92Some Best Practices for Action ......................................................................................................... 94More Best Practices for Action ......................................................................................................... 96Labs ................................................................................................................................................. 98

Chapter 6 - The View ........................................................................................................................... 101

Forwarding to a View ..................................................................................................................... 102Overview of Struts Tags .................................................................................................................. 104Struts HTML Tags .......................................................................................................................... 106Form-Related Tags ......................................................................................................................... 108Dealing with URLs .......................................................................................................................... 110Using Error Tags ............................................................................................................................. 112Displaying Messages ....................................................................................................................... 114Struts Bean Tags ............................................................................................................................. 116Struts Logic Tags ............................................................................................................................ 118Some Struts View Best Practices .................................................................................................... 120Labs ............................................................................................................................................... 122

Page 5: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

© 2011 ITCourseware, LLC Rev 1.3.2 Page v

Struts

Chapter 7 - Internationalization .............................................................................................................. 125

I18N and L10N.............................................................................................................................. 126Resource Bundles ........................................................................................................................... 128Java's MessageFormat Class ........................................................................................................... 130Internationalization in Struts ............................................................................................................. 132I18N with Struts Tags ..................................................................................................................... 134I18N with JSTL tags ....................................................................................................................... 136I18N within Java Code ................................................................................................................... 138Labs ............................................................................................................................................... 140

Chapter 8 - Advanced Struts Features .................................................................................................. 143

Accessing Bean Properties .............................................................................................................. 144DynaActionForm: A Configurable Form ......................................................................................... 146Indexed and Mapped Properties in a Form ..................................................................................... 148Using indexed="true" ....................................................................................................................... 150Preventing Duplicate Form Submits ................................................................................................. 152Using ForwardAction and IncludeAction ......................................................................................... 154DispatchAction ............................................................................................................................... 156LookupDispatchAction ................................................................................................................... 158Implementing a LookupDispatchAction ........................................................................................... 160Labs ............................................................................................................................................... 162

Chapter 9 - Handling Errors .................................................................................................................. 165

Error Handling Options with Struts .................................................................................................. 166Documenting Errors with ActionMessage ........................................................................................ 168JSP Error Pages .............................................................................................................................. 170Declarative Java Exception Handling ............................................................................................... 172Logging in Struts ............................................................................................................................. 174Labs ............................................................................................................................................... 176

Chapter 10 - Validation ......................................................................................................................... 179

Validator Overview ......................................................................................................................... 180Validator Requirements ................................................................................................................... 182Configuring Validator Rules ............................................................................................................. 184Struts Validators .............................................................................................................................. 186

Page 6: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Page vi Rev 1.3.2 © 2011 ITCourseware, LLC

Struts

Configuring the Struts Validators ...................................................................................................... 188Configuring Form Validation — global and formset .......................................................................... 190Configuring Form Validation — form and field ................................................................................. 192Configuring Form Validation — arg ................................................................................................. 194Configuring Form Validation — var ................................................................................................. 196Validation with Regular Expressions ................................................................................................. 198ValidatorForm vs. ValidatorActionForm .......................................................................................... 200Implementing a Validator Method .................................................................................................... 202Other Validator Implications ............................................................................................................ 204Labs ............................................................................................................................................... 206

Chapter 11 - Page Composition with Tiles ............................................................................................. 209

Tiles Overview ................................................................................................................................ 210Building a Tiles Template ................................................................................................................. 212Basic Tiles Example......................................................................................................................... 214Tiles Definitions ............................................................................................................................... 216Additional Options with Definitions .................................................................................................. 218Placing Definitions in a Configuration File......................................................................................... 220Using the <put> Tag ........................................................................................................................ 222Enabling the Tiles Plug-In ................................................................................................................ 224Using Tiles....................................................................................................................................... 226Labs ............................................................................................................................................... 228

Appendix - Nested Tags ....................................................................................................................... 231

Why Nested Tags?.......................................................................................................................... 232Using Nested Tags .......................................................................................................................... 234Parent and Root Tags ...................................................................................................................... 236

Solutions ............................................................................................................................................... 239

Index..................................................................................................................................................... 323

Page 7: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Course Introduction

© 2011 ITCourseware, LLC Rev 1.3.2 Page 7

Chapter 1

Chapter 1 - Course Introduction

Page 8: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 8 Rev 1.3.2 © 2011 ITCourseware, LLC

Describe how Struts fit in a Java application server environment.

Use Struts to implement an MVC web application design.

Configure a Struts application using struts-config.xml and web.xml.

Build a JSP view using Struts and JSTL tags.

Handle form validation, error processing, and logging in a Strutsenvironment.

Use the Struts Tiles facilities to make the look and feel of a web applicationflexible and easy to maintain.

Course Objectives

Page 9: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Course Introduction

© 2011 ITCourseware, LLC Rev 1.3.2 Page 9

Chapter 1

Page 10: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 10 Rev 1.3.2 © 2011 ITCourseware, LLC

Audience: Experienced Java Servlet and JSP developers who need to useStruts as a framework for MVC web application development.

Prerequisites: Java Programming and Java Web Programming.

Classroom Environment:

A workstation per student.

Course Overview

Page 11: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Course Introduction

© 2011 ITCourseware, LLC Rev 1.3.2 Page 11

Chapter 1

Using the Workbook

Chapter 2 Servlet Basics

© 2002 ITCourseware, LLC Rev 2.0.0 Page 17

Add an init() method to your Today servlet that initializes a bornOn date, then print the bornOn date

along with the current date:

Today.java

...

public class Today extends GenericServlet {

private Date bornOn;

public void service(ServletRequest request,

ServletResponse response) throws ServletException, IOException

{

...

// Write the document

out.println("This servlet was born on " + bornOn.toString());

out.println("It is now " + today.toString());

}

public void init() {

bornOn = new Date();

}

}

Hands On:

The init() method is

called when the servlet is

loaded into the container.

This workbook design is based on a page-pair, consisting of a Topic page and a Support page. When youlay the workbook open flat, the Topic page is on the left and the Support page is on the right. The Topicpage contains the points to be discussed in class. The Support page has code examples, diagrams, screenshots and additional information. Hands On sections provide opportunities for practical application of keyconcepts. Try It and Investigate sections help direct individual discovery.

In addition, there is an index for quick look-up. Printed lab solutions are in the back of the book as well ason-line if you need a little help.

Java Servlets

Page 16 Rev 2.0.0 © 2002 ITCourseware, LLC

� The servlet container controls the life cycle of the servlet.

� When the first request is received, the container loads the servlet class

and calls the init() method.

� For every request, the container uses a separate thread to call

the service() method.

� When the servlet is unloaded, the container calls the destroy()

method.

� As with Java’s finalize() method, don’t count on this being

called.

� Override one of the init() methods for one-time initializations, instead of

using a constructor.

� The simplest form takes no parameters.

public void init() {...}

� If you need to know container-specific configuration information, use

the other version.

public void init(ServletConfig config) {...

� Whenever you use the ServletConfig approach, always call the

superclass method, which performs additional initializations.

super.init(config);

The Servlet Life Cycle

The Topic page providesthe main topics for

classroom discussion.

The Support page hasadditional information,

examples and suggestions.

Code examples are in afixed font and shaded. Theon-line file name is listedabove the shaded area.

Screen shots showexamples of what youshould see in class.

Topics are organized intofirst ( ), second ( ) and

third ( ) level points.

Pages are numberedsequentially throughout

the book, making lookupeasy.

Callout boxes point outimportant parts of the

example code.

Page 12: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 12 Rev 1.3.2 © 2011 ITCourseware, LLC

Carnell, John and Rob Harrop. 2004. Pro Jakarta Struts, Second Edition. APress L.P.,Berkeley, CA. ISBN 159059228X

Cavaness, Chuck and Brian Keeton. 2003. Jakarta Struts Pocket Reference. O'Reilly &Associates, Sebastopol, CA. ISBN 0596005199

Cavaness, Chuck. 2004. Programming Jakarta Struts. O'Reilly & Associates, Sebastopol, CA.ISBN 0596006519

Franciscus, George and Danilo Gurovich. 2004. Struts Recipes. Manning Publications,Greenwich, CT. ISBN 1932394249

Friedl, Jeffrey. 2002. Mastering Regular Expressions, Second Edition. O'Reilly & Associates,Sebastopol, CA. ISBN 0596002890

Goodwill, James and Richard Hightower. 2003. Professional Jakarta Struts. Wrox Press/WileyPublishing, Inc., Indianapolis, IN. ISBN 0764544373

Holmes, James and Herbert Schildt. 2004. Struts: The Complete Reference. Osborne/McGraw-Hill, Emeryville, CA. ISBN 0072231319

Husted, Ted, Cedric Dumoulin, George Franciscus, and David Winterfeldt. 2002. Struts inAction: Building Web Applications with the Leading Java Framework. ManningPublications, Greenwich, CT. ISBN 1930110502

Kurniawan, Budi. 2005. Struts Design and Programming: A Tutorial. BrainySoftware.com,Vancouver, BC, Canada. ISBN 0975212818

Shenoy, Srikanth and Nithin Mallya. 2004. Struts Survival Guide: Basics to Best Practices.Objectsource LLC, Austin, TX. ISBN 0974848808

Siggelkow, Bill. 2005. Jakarta Struts Cookbook. O'Reilly & Associates, Sebastopol, CA.ISBN 059600771X

Spielman, Sue. 2002. The Struts Framework: Practical Guide for Java Programmers.Morgan Kaufman Publishers, San Francisco, CA. ISBN 1558608621

http://struts.apache.orghttp://java.sun.com

Suggested References

Page 13: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Course Introduction

© 2011 ITCourseware, LLC Rev 1.3.2 Page 13

Chapter 1

Page 14: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 14 Rev 1.3.2 © 2011 ITCourseware, LLC

Page 15: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Chapter 2 Struts Overview

© 2011 ITCourseware, LLC Rev 1.3.2 Page 15

Chapter 2 - Struts Overview

Objectives

Describe how Struts fits into a Java webapplication.

Identify the major components of theMVC Model 2 application design.

Outline the basic flow through a webapplication using Struts.

Page 16: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 16 Rev 1.3.2 © 2011 ITCourseware, LLC

Struts is an open source Java web application framework based on the Model-View-Controller design pattern.

It is based upon proven design patterns and published Java-basedstandards.

The name is a reference to the concept of struts in the architectural sense— struts form the skeleton of a building or bridge.

Struts provides a solid basis for a framework that is easily extensible.

Struts framework classes can be easily extended to add or modifyfunctionality.

Struts facilitates change in web applications and specialization of developmentteam members.

Struts is an Apache Jakarta project sponsored by the Apache SoftwareFoundation.

For more information, see: http://struts.apache.org

Struts uses Jakarta Commons projects, see: http://jakarta.apache.org/commons/.

BeanUtils — JavaBean utility classesValidator — Java and JavaScript form validationDigester — An XML parser that facilitates the conversion of XML to

objectsCollections — Some simple, fast collection utility classesLogging — An interface to several prominent logging technologies

What is Struts?

Page 17: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Chapter 2 Struts Overview

© 2011 ITCourseware, LLC Rev 1.3.2 Page 17

The Apache Struts project has been broken into two frameworks: Stuts Action Framework and StrutsShale Framework.

The Struts Action Framework is the new name for what has traditionally been called Struts. It continuessupport and development on the request-based JSP framework that has been used in production since2001. In this course, we will be studying the Struts Action Framework.

The Struts Shale Framework is a new project that builds on five years of learning and technology advances.It embraces the JavaServer Faces (JSF) component model and allows for integration with other popularframeworks, such as Spring.

Page 18: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 18 Rev 1.3.2 © 2011 ITCourseware, LLC

Model 1 Design Pattern

Servlet and JSP development typically involves several technologies and skills:

JavaJSPHTML, XHTML, XML, XSLTCSSJavaScript

Co-mingling Java and JavaScript can make pages difficult to follow.

Coupling business logic and presentation logic can also cause problems.

It is difficult to modify the website appearance.

Changes in business rules can necessitate retesting of the web application.

Embedded flow of control can be difficult to follow.

A web application is a more complex debugging environment.

Servlets and JSPs make it easy to build simple inquiry sites.

Page 19: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Chapter 2 Struts Overview

© 2011 ITCourseware, LLC Rev 1.3.2 Page 19

MVC Model 1

Client

web browser

Servlet

or

JSP

JavaBean(s)

or

Enterprise

JavaBean(s)

HTTP Request

HTTP Response

Page 20: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 20 Rev 1.3.2 © 2011 ITCourseware, LLC

The model:

Encapsulates the function of an application, including its internal state andactions to change its state.

Typically knows nothing about the data presentation (view) or theapplication flow (control).

Can use many Java-based technologies, such as JavaBeans, EnterpriseJavaBeans, JDBC, etc.

Components are not necessarily dependent upon a web containerenvironment.

The view:

Is a presentation of the model.

Retrieves data with the accessor methods of a model, but knows nothingabout the controller.

Should be notified when the model changes (state change).

The controller:

Reacts to user input and delegates the request.

Creates and initializes the model with user information.

Mediates flow, determining the flow required to handle a request.

Is frequently directed by external configuration files, such as XML files.

Model 2 / MVC Design Pattern

Page 21: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Chapter 2 Struts Overview

© 2011 ITCourseware, LLC Rev 1.3.2 Page 21

A typical J2EE MVC application flow:

1. The browser makes an HTTP request. The web container forwards the request to the controllerassigned to this kind of request.

2. The controller (usually a servlet), invokes business tier logic via the model. This may involve EJB and/orJDBC.

3. New or updated information is returned to the controller via the model.

4. The controller passes the new information to the appropriate view (usually a JSP).

5. The new view is returned to the browser via an HTTP response.

Web Container

Browser

Controller

Model View

EJB ContainerEJB

1

2 3 4

5

Database

Page 22: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 22 Rev 1.3.2 © 2011 ITCourseware, LLC

Frameworks such as Struts provide a generic implementation of the MVCdesign pattern so that the developer can focus on the application requirements,rather than the MVC architecture.

Some functions of the framework:

To be declarative (XML) rather than code-driven (Java).

Map the incoming request to the application processing components.

Handle form input.

Provide error handling support.

Provide forwarding support, particularly for the view.

Provide for internationalization of views.

Assist in the development of a JSP.

Provide for user extensions.

Implementing MVC with a Framework

Page 23: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Chapter 2 Struts Overview

© 2011 ITCourseware, LLC Rev 1.3.2 Page 23

Page 24: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 24 Rev 1.3.2 © 2011 ITCourseware, LLC

Struts is a group of configurable components designed for use in a Model 2 /MVC application design.

All parts of the Struts framework can be extended.

The Struts controller is configurable.

The main controller is a Java servlet called ActionServlet.

It uses other controller component classes, including RequestProcessor,ActionForm, ActionMapping, Action, ActionForward, andActionError.

The Struts model interfaces with a user model.

There are no specific model components to Struts.

Struts can use existing Java-based technologies, such as JavaBeans, EJB,and JDBC.

There are typically beans that execute business logic and other beans thatpersist data.

The Struts view is based on JSP technology.

View components are typically JSPs.

Struts includes extensive tag libraries and Velocity templates.

Struts can incorporate other web technologies, such as static template text(HTML, XML), dynamic content from other servlets and JSPs, and XSLT.

The Struts Framework

Page 25: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Chapter 2 Struts Overview

© 2011 ITCourseware, LLC Rev 1.3.2 Page 25

A typical J2EE Struts application flow:

1. The browser makes an HTTP request. The web container forwards the request to the Struts controller(ActionServlet). The ActionServlet passes the request to the appropriate Action that has beencoded to deal with this request.

2. The Action invokes the business tier logic with the form bean (ActionForm). This may involve EJBand/or JDBC.

3. New or updated information is returned to the controller via the model (form bean).

4. The controller passes the new information (form beans and other JavaBeans) to the appropriate view(usually a JSP).

5. The new view is returned to the browser via an HTTP response.

Web Container

Browser

Controller

(Action Servlet)

Model View

EJB ContainerEJB

1

2 3 4

5

Action

Database

Page 26: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 26 Rev 1.3.2 © 2011 ITCourseware, LLC

An ActionMapping is an encapsulation of how an HTTP request path ismapped to a specific Action.

An ActionServlet is an implementation of the command design pattern.

The user agent creates an HTTP event.

The web container creates an HTTP request and follows the mapping tothe ActionServlet.

All of the processing for a web context goes through one ActionServlet.

ActionForm beans, often called "form beans," mediate between the model andthe view.

They are created and set by the controller.

They can contain validation.

They represent the request and response state, not the persistent businessdata.

The controller passes the request, response, mapping information, and the formbean to the execute() method of your Action subclass.

Your execute() method should implement the business logic as a thinwrapper, or better still, act as a delegate to business beans.

Your implementation may act as an adapter that converts the form dataand request into data that the business components expect.

Basic Struts Components

Page 27: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Chapter 2 Struts Overview

© 2011 ITCourseware, LLC Rev 1.3.2 Page 27

Page 28: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 28 Rev 1.3.2 © 2011 ITCourseware, LLC

An ActionForward maps a logical name to a destination.

The Action determines what view or subsequent Action should getcontrol next by requesting a symbolically-referenced ActionForward.

ActionForwards are configured in struts-config.xml and, thus, looselycoupled to the application.

ActionErrors and ActionMessages contain lists of messages that can bepassed to a view to be displayed with Struts tags.

struts-config.xml contains configuration information for Struts, form beans,actions, mappings, forwarding, and exception handling.

web.xml configures the ActionServlet and its servlet mapping, and locates thestruts-config.xml file.

Struts tag libraries assist in the preparation of a JSP view.

Basic Struts Components (cont'd)

Page 29: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Chapter 2 Struts Overview

© 2011 ITCourseware, LLC Rev 1.3.2 Page 29

Page 30: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 30 Rev 1.3.2 © 2011 ITCourseware, LLC

The struts documentation can be found online at http://struts.apache.org/struts-action/index.html.

The User Guide contains the basic specifications for Struts.

General overview information on each of the components, and how tobuild the struts-config.xml file, can be found at userGuide/index.html.

More detailed information is available in the JavaDoc API documentation.

Struts FAQs and How to Guides contain useful links, samples, and answers tobasic questions.

There is separate documentation for the tag libraries and utilities.

It can be found at http://struts.apache.org/struts-taglib/index.html.

Documentation for the Apache Foundation Commons Components, such asLogging and Validator, can be found at http://jakarta.apache.org/commons/index.html.

You'll probably want documentation for Java and the web container, as well.

Struts Documentation

Page 31: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Chapter 2 Struts Overview

© 2011 ITCourseware, LLC Rev 1.3.2 Page 31

Page 32: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 32 Rev 1.3.2 © 2011 ITCourseware, LLC

The client initiates a logon request.

The web container creates an HttpServletRequest object and passes it tologon.jsp.

The HttpServletResponse of the JSP returns a logon form.

The client completes the logon form (user and password parameters) andsubmits it to /logon.do.

The web container creates an HttpServletRequest object and follows a servletmapping specified in web.xml to the ActionServlet (the Struts controller).

The controller creates an ActionMapping indicating that the request path was"/logon" and that control should go to the LogonAction, with its parameterssaved in an instance of LogonForm.

This is often referred to as a switchboard action.

The LogonAction execute() method validates the logon.

If valid, control goes to a welcome page (welcome.jsp) logically specifiedin struts-config.xml as "success" after saving the user in the HttpSessionobject.

If invalid, an error message is added and control returns to the input page(logon.jsp) to be displayed on the logon page.

The valid (welcome.jsp) or invalid (logon.jsp) JSP is invoked by the webcontainer and the response it generates is returned to the client.

A Struts-Based Application: Logon

Page 33: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Chapter 2 Struts Overview

© 2011 ITCourseware, LLC Rev 1.3.2 Page 33

Struts comes as a ZIP file that includes the documentation as a WAR file. You can access it through a webserver or view it offline with a browser. To compile a Java component that uses Struts, several JAR files areneeded in the classpath, including struts.jar and your application server's JAR file that contains the ServletAPI. The Apache Commons packages have JARs that may be needed, as well.

To use Struts in a web application, struts.jar and other Common's JARs, such as commons-logging.jar, commons-beanutils.jar, and commons-digester.jar, from the <strutsInstall>\lib must beavailable to your application.

To simplify the building and deployment process, we will use the Apache Software Foundation's Ant tool.To use Ant, you create an XML configuration file called build.xml and define targets that define the stepsfor building and deploying your application. The targets also set dependencies, so that you can compile,build, and deploy with a single command.

For this class, we have provided build.xml files for you. They contain the proper classpath settingsand targets for compiling the Java files, building the WAR file, and deploying the WAR file.

Try It:To test the Logon application that is described on the previous page, perform the following steps:

1. Start your application server or web container.2. Run the Ant command in the chapter directory.3. Open a browser and go to http://localhost:port/Logon to retrieve a logon form.4. Logon with student and password.5. Try again with student and any invalid password.6. Try again with your own name and password.

Your instructor will give you the details of how to start the server, run Ant, and which port to usewithin the URL.

Page 34: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 34 Rev 1.3.2 © 2011 ITCourseware, LLC

Use the Struts API documentation to answer the following questions:

a. What package contains ActionServlet, ActionForm, and Action?b. What is the return type of the Action execute() method?c. What is the signature of the ActionForm validate() method?d. Where is information regarding the Struts Validator?e. Does the Struts HTML tag library contain a <hidden> tag?(Solution: lab1.txt)

Where is the struts-config.xml file located for the Logon application?(Solution: lab2.txt)

Look through the struts-config.xml file and see if you can determine where the text for theerror messages used in the views of the logon application can be found.(Solution: lab3.txt)

Start a browser and enter http://localhost:port/Logon/. Your instructor will tell you the correctport to use for your application server. How does it get to logon.jsp?Hint: Look at web.xml.(Solution: lab4.txt)

Labs

Page 35: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Chapter 2 Struts Overview

© 2011 ITCourseware, LLC Rev 1.3.2 Page 35

Page 36: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 36 Rev 1.3.2 © 2011 ITCourseware, LLC

Page 37: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Chapter 8 Advanced Struts Features

© 2011 ITCourseware, LLC Rev 1.3.2 Page 143

Chapter 8 - Advanced Struts Features

Objectives

Access complex JavaBean properties.

Reduce the number of ActionForm classes inyour application with DynaActionForm.

Use DispatchAction andLookupDispatchAction when you want to usethe same action class for multiple, related tasks.

Page 38: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 144 Rev 1.3.2 © 2011 ITCourseware, LLC

There are four different ways to reference a bean property from a Struts HTMLtag's property attribute.

When you specify the simple name of the property, Struts uses reflection todetermine the appropriate JavaBean accessor or mutator method.

This is equivalent to the <jsp:getProperty> and <jsp:setProperty> tags.

When you want to access a property of a property, you can use a nestedproperty reference.

The property names are linked with periods that are translated to a seriesof accessor methods.

property="customer.address.zipCode" becomesgetCustomer().getAddress().getZipCode().

When setting a property, the set method is called on the last property:getCustomer().getAddress().setZipCode(newZipCode).

An indexed property reference uses get and set methods that take an indexparameter, allowing for indexed access of an array property.

property="lineItem[2]" translates to getLineItem(2) or setLineItem(2,someValue).

You can also nest indexed properties.

property="orders.order[0].lineItem[0]" translates togetOrders().getOrder(0).getLineItem(0).

Beware that all properties must exist or exceptions could be thrown.

Accessing Bean Properties

Page 39: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Chapter 8 Advanced Struts Features

© 2011 ITCourseware, LLC Rev 1.3.2 Page 145

This becomesgetNewBook().getYear().

demo.jsp<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<html:html><head>

<title>Dyna Form and Property Demo</title><html:base/>

</head><body>

<h3>Dyna Form and Property Demo</h3><html:form action="/demo" >

<table><tr>

<td colspan="2">Add the title, author, and year for a new book

</td></tr><tr>

<th align="right">Title</th><td align="left"><html:text property="newBook.title"/></td>

</tr><tr>

<th align="right">Author</th><td align="left"><html:text property="newBook.author"/></td>

</tr><tr>

<th align="right">Copyright Year</th><td align="left"><html:text property="newBook.year"/></td>

</tr><tr>

<td align="right" colspan="2"><html:submit>Submit</html:submit>

</td></tr><tr>

<td colspan="2">Just saw the new title: ${requestScope.newTitle}

</td></tr>

</table>...

The form contains a newBook property that is a demo.Book with properties of title, author, and year.

Page 40: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 146 Rev 1.3.2 © 2011 ITCourseware, LLC

Use DynaActionForm to reduce the number of ActionForm classes that youhave to develop.

DynaActionForm is an ActionForm that you can configure in struts-config.xml.

You can specify individual properties, their datatype, and any defaults.

No other form properties will be recognized in the DynaActionForm.

DynaActionForm supports arrays.

Specify [ ] at the end of the property type and provide an initialvalue or a size (zero is allowed).

The arrays can contain primitive or object elements.

The DynaActionFrom stores the properties in an internal map.

Use map-style get() and set() methods to access the properties from anaction or form.

(String)((DynaActionForm)form).get("candy");

The cast is required because the get() method returns an Object.

You can extend DynaActionForm to override the validate() or reset() method.

Or you can use the validator with anorg.apache.struts.validator.DynaValidatorForm.

DynaActionForm: A Configurable Form

Page 41: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Chapter 8 Advanced Struts Features

© 2011 ITCourseware, LLC Rev 1.3.2 Page 147

Use [ ] to denote an array.

struts-config.xml...

<form-beans><form-bean name="demoDynaForm"

type="org.apache.struts.action.DynaActionForm" ><form-property name="title" type="java.lang.String"/><form-property name="author" type="java.lang.String"/><form-property name="year" type="java.lang.String"/><form-property name="newBook" type="demo.Book"/><form-property name="bookArray" size="2" type="demo.Book[]"/><form-property name="bookMap" type="java.util.Map"/>

</form-bean></form-beans>

...

The types supported by DynaActionForm include:

java.lang.BigDecimaljava.lang.BigIntegerboolean and java.lang.Booleanbyte and java.lang.Bytechar and java.lang.Characterjava.lang.Classdouble and java.lang.Doublefloat and java.lang.Floatint and java.lang.Integerlong and java.lang.Longshort and java.lang.Shortjava.lang.Stringjava.sql.Datejava.sql.Timejava.sql.TimestampArrays of the aboveConcrete implementations of java.util.Map or java.util.ListBeans and bean arrays (if only the bean properties are used as parameters)

Note:Only objects can be stored in the Map of a DynaActionForm. So, while primitives may be specified, theyare not useful except as primitive arrays. Just as with regular form beans, all fields in your HTML formshould be mapped to Strings in your DynaActionForm.

demoDynaForm contains six properties.

Page 42: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 148 Rev 1.3.2 © 2011 ITCourseware, LLC

What if a view is generated dynamically at request time with an unknownnumber and type of properties to be processed in an action?

One or more properties in an ActionForm (even a DynaActionForm) can be ajava.util.Map, a java.util.Collection, or an array.

public void setMapValue(String key, Object value) {map.put(key, value);

}public Object getMapValue(String key) {

return map.get(key);}public void setListValue(int index, Object value){

list.set(index, value);}public Object getListValue(int index) {

return list.get(index);}

Make sure to create and optionally populate the array, Collection, orMap.

Access an individual element in a JSP with special syntax:

<html:text property="mapValue(theKey)" /><html:text property="listValue[theIndex]" />

Loop through all of the elements in the Map, Collection, or array with the<c:forEach> tag.

Indexed and Mapped Properties in a Form

Page 43: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Chapter 8 Advanced Struts Features

© 2011 ITCourseware, LLC Rev 1.3.2 Page 149

The JSTL forEach tag usesthe map property of the

DynaActionForm to accessthe dynamic properties.

demo.jsp...

<h3>Iteration over the book array:</h3><table>

<tr><th>IndexID</th><th>Title</th><th>Author</th></tr><c:forEach var="nextBook" varStatus="status"

items="${demoDynaForm.map.bookArray}"><tr>

<td>${status.index}</td><td>${nextBook.title}</td><td>${nextBook.author}</td>

</tr></c:forEach>

</table>

<h3>Iteration over the book map:</h3><table>

<tr><th>IndexID</th><th>Title</th><th>Author</th></tr><c:forEach var="nextMapEntry" varStatus="status"

items="${demoDynaForm.map.bookMap}"><tr>

<td>${status.index}</td><td>${nextMapEntry.key}</td><td>${nextMapEntry.value.author}</td>

</tr></c:forEach>

</table>...

Page 44: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 150 Rev 1.3.2 © 2011 ITCourseware, LLC

Using indexed="true"

The indexed="true" attribute on many of the form-related tags will add indexvalues to the name in an HTML tag when it is generated in the body of<c:forEach> or <logic:iterate>.

Generated index values within the body of <c:forEach> or <logic:iterate >:

sgaTLMTHsturtS LMTHdetareneGnehwtamrofeman

"eurt"=dexednideddasietubirtta

LRUdetareneGretemarapyreuq

,neddih,elif,xobkcehc,oidar,drowssap

aeratxet,txet,tceles

[eman nn ytreporp.]

timbus,egami,nottub [ytreporp nn ]

knil =xedni nn ro=mun nn erehw

"=dexedni mun "

Page 45: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Chapter 8 Advanced Struts Features

© 2011 ITCourseware, LLC Rev 1.3.2 Page 151

demo.jsp...

<h3>Iteration over the book array with indexed="true":</h3><table>

<c:forEach var="nextBook"items="${demoDynaForm.map.bookArray}">

<tr><td>

<html:text name="nextBook" property="title"indexed="true" size="60" />

</td></tr>

</c:forEach></table>

...

When you view the source of the rendered demo.jsp in your browser, it looks something like this:

snippet.txt<h3>Iteration over the book array with indexed="true":</h3><table>

<tr><td>

<input type="text" name="nextBook[0].title" size="60"value="Programming Jakarta Struts">

</td></tr><tr>

<td><input type="text" name="nextBook[1].title" size="60"

value="Struts Kick Start"></td>

</tr></table> indexed="true" adds an

index value for each elementin the generated HTML.

Page 46: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 152 Rev 1.3.2 © 2011 ITCourseware, LLC

Dealing with duplicate submissions can be a problem for web applications insome containers.

Struts provides a facility that detects duplicate submissions.

Generate a token to identify a submission as part of the preconditionprocessing of an action.

saveToken(request);

A numeric token is placed in the session object as aGlobals.TRANSACTION_TOKEN_KEY attribute.

<html:form>, <html:link … transaction="true" >, or<html:rewrite … transaction="true"> tags automaticallygenerate code in the view that includes a hidden field.

<input type="hidden" name="Constants.TOKEN_KEY"value="session token" />

Test for the validity of a token as part of the precondition processing ofan action.

boolean validReq = isTokenValid(request);

Return some sort of error response to the client.

if (!validReq) return findForward(DUPLICATE_REQ);

Reset the token for the next turnaround.

resetToken(request);

Precondition processing can also check for the presence of a cancel (button)request.

boolean cancelled = isCancelled(request);

Preventing Duplicate Form Submits

Page 47: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Chapter 8 Advanced Struts Features

© 2011 ITCourseware, LLC Rev 1.3.2 Page 153

Page 48: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 154 Rev 1.3.2 © 2011 ITCourseware, LLC

ForwardAction and IncludeAction are Action extensions designed to facilitatethe use of existing JSP and servlet applications within a Struts application.

A ForwardAction forwards control to another resource (action, JSP, servlet, orURI) using a request diapatcher.

Use a ForwardAction to facilitate future application changes that mightincorporate the facilities of Struts.

It provides an action that can be used to present an empty form, andbypass validation and processing of the form.

It passes along any request parameters and attributes, session, and localethat may have been created earlier in the processing and could beretrieved in a servlet.

An IncludeAction generates an include directive for the resource specified inthe parameter attribute of an action and not tightly coupled to the currentprocessing.

This allows for the inclusion of output during the preparation of theresponse as control returns to the calling resource.

It is useful for a dynamically-generated header or footer, or to allow thecompletion of a segment of the processing by another application.

It can also allow the use of a resource that does not use Struts.

Using ForwardAction and IncludeAction

Page 49: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Chapter 8 Advanced Struts Features

© 2011 ITCourseware, LLC Rev 1.3.2 Page 155

IncludeAction example.

ForwardAction example.actionexamples.txt<action path="/myPath"

type="org.apache.struts.actions.ForwardAction"name="myForm"scope="request"input="/myPath.jsp"parameter="/pathToTheResource" />

<action path="/myPath"type="org.apache.struts.actions.IncludeAction"name="myForm"scope="request"input="/myPath.jsp"parameter="/pathToTheResource" />

Below is an excerpt from the Book Club struts-config.xml illustrating the use of ForwardAction to presentan empty logon (bookClubLogon.jsp) form.

bookClubStarterCode/struts-config.xml...<action path="/logonReq" type="org.apache.struts.actions.ForwardAction" parameter="/pages/bookClubLogon.jsp"></action>...

There are several other ways to accomplish includes:

The JSP <%@include file="relativeURL" %> include directive performs the include attranslation time, as if the file was part of the current JSP.

The JSP <jsp:include page="relativeURL" … /> allows the inclusion of a static resource or theresults of a dynamic resource at request time. It can be run conditionally, using tags or scriptlets.

The <bean:include> tag with a forward, href, or page attribute, and the id attribute opens aconnection to the URL calculated at request time and saves the input received from it as a String undera page scope attribute whose name is the value of the id attribute of the tag. The saved string canbe used in the page presentation using other tags or scriptlets. The <bean:include> execution canbe conditional with the use of other tags or scriptlets.

Page 50: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 156 Rev 1.3.2 © 2011 ITCourseware, LLC

org.apache.struts.actions.DispatchAction's execute() method passes controlto another action method named by a request parameter.

This allows you to create an action that handles related processing thathas been isolated in individual methods.

Create a subclass of org.apache.struts.actions.DispatchAction.

Add a method with the same return value and parameter list as execute()for each of the related processes (for example, create(), read(),update(), and delete()).

Make sure to keep all of the processing methods and helpermethods thread safe.

Configure the use of the DispatchAction subclass:

<action path="/myUnifiedAction" type="myOrg.app.MyUnifiedDispatchAction" name="myForm" scope="request" input="/myUnifiedInput.jsp" parameter="method" />

The parameter attribute names the request parameter that will contain theaction's method that should be run.

Invoke the appropriate process with the specified parameter:

http://myhost/app/myUnifiedAction.do?method=create

You often specify the method parameter with the value of a button or a hiddenfield set with JavaScript.

DispatchAction

Page 51: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Chapter 8 Advanced Struts Features

© 2011 ITCourseware, LLC Rev 1.3.2 Page 157

No JavaScriptrequired, but you can'tinternationalize, either.

Now button labels comefrom the resource bundle.

When you pass the method parameter with a button, there is no JavaScript requirement. Button labelsmatch method names passed with the method parameter. Because the value must match the method namein the DispatchAction subclass, button labels cannot be internationalized.

<html:submit property="method" value="create" /><html:submit property="method" value="read" /><html:submit property="method" value="update" /><html:submit property="method" value="delete" />

When you pass the method parameter with a hidden field and buttons, JavaScript is required in the browser.This allows you to internationalize the button labels.

<html:hidden property="method" /><html:submit

onclick='document.forms["myForm"].method.value="create";document.forms["myForm"].submit();' ><fmt:message key="myForm.submit.create" />

</html:submit><html:submit

onclick='document.forms["myForm"].method.value="read";document.forms["myForm"].submit();' ><fmt:message key="myForm.submit.read" />

</html:submit><html:submit

onclick='document.forms["myForm"].method.value="update";document.forms["myForm"].submit();' ><fmt:message key="myForm.submit.update" />

</html:submit><html:submit

onclick='document.forms["myForm"].method.value="delete";document.forms["myForm"].submit();' ><fmt:message key="myForm.submit.delete" />

</html:submit>

Note:The default property attribute value for the <html:submit> tag is "submit" and could be used withparameter="submit" in the action configuration.

Page 52: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 158 Rev 1.3.2 © 2011 ITCourseware, LLC

LookupDispatchAction is an extension of DispatchAction that solves thelocalization consideration where the value on the view that invokes the action(e.g. a button) may be locale-dependent.

In struts-config.xml, configure the action with a parameter attribute whosevalue matches the property attribute on a Struts submit tag ("method").

<action path="/myLookupAction" type="myOrg.app.MyLookupDispatchAction" parameter="method" />

Add locale-dependent values for the submit button in the application's resourcebundles.

button.create=Add Memberbutton.delete=Delete Member

The keys will be used to create a java.util.Map that relates keys tomethod names in a locale-independent fashion.

The value of the key attribute of the message tag is used to look up theinternationalized label on the submit button.

<html:form action="/myLookupAction" ><html:submit property="method" >

<fmt:message key="button.create" /></html:submit><html:submit property="method" >

<fmt:message key="button.delete" /></html:submit>

</html:form>

LookupDispatchAction

Page 53: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Chapter 8 Advanced Struts Features

© 2011 ITCourseware, LLC Rev 1.3.2 Page 159

DispatchAction and LookupDispatchAction provide a framework for related tasks that may be analternative to chained actions.

Page 54: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 160 Rev 1.3.2 © 2011 ITCourseware, LLC

Extend LookupDispatchAction and implement the abstractgetKeyMethodMap() method.

Associate the resource bundle keys with the method names in the Map.

protected Map getKeyMethodMap(ActionMapping mapping,ActionForm form, HttpServletRequest request) {

Map map = new HashMap();map.put("button.create", "create");map.put("button.delete", "delete");return map;

}

Implement each method named as a value in the Map:

public ActionForward create (ActionMapping mapping,ActionForm form, HttpServletRequest request,HttpServletResponse response) throws Exception {

// do the create processingreturn mapping.findForward("success");

}public ActionForward delete(ActionMapping mapping,

ActionForm form, HttpServletRequest request,HttpServletResponse response) throws Exception {

// do the delete processingreturn mapping.findForward("success");

}

Implementing a LookupDispatchAction

Page 55: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Chapter 8 Advanced Struts Features

© 2011 ITCourseware, LLC Rev 1.3.2 Page 161

Note:The ForwardAction, IncludeAction, DispatchAction, and LookupDispatchAction are all members ofthe org.apache.struts.actions package. This package is part of the Struts Action-Extras subproject. Seehttp://struts.apache.org/struts-action/struts-extras/index.html for more information.

Page 56: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Struts

Page 162 Rev 1.3.2 © 2011 ITCourseware, LLC

Use the bookClubStarterCode directory, or your solutions to the previous labs, as the basis for labs and .

Modify bookClub.club.BookForm to use a DynaActionForm.

a. Extend DynaActionForm rather than ActionForm.

b. Remove the unneeded fields, and accessor and mutator methods.

c. Update the validate() method to use properties from the parent DynaActionForm.

d. Configure it in struts-config.xml.

e. Make any necessary changes to your AddBookAction.(Solutions: bookClub/BookForm.java, bookClub/AddBookAction.java, bookClub/struts-config.xml)

Test your Book Club application by adding a book.

Use the BookClubStarterCode directory as the basis for the rest of the labs.

Modify logon.LogonAction to extend DispatchAction instead of Action.

a. Put the logon functionality in a method called logon with the same return value andparameter list as the execute() method. Remove the execute() method.

b. Add a logoff() method with the same return value and parameter list as the logon()method.

i. Remove the username from the session, if one is present.

ii. If a username is present, add an ActionMessage containing the username as adynamic argument and place the appropriate message in themessages.properties file.

iii. Return the logon forward.(Solutions: logon/LogonAction.java, logon/messages.properties)

Labs

Page 57: Struts - ITCourseware · The Apache Struts project has been broken into two frameworks: Stuts Action Framework and Struts Shale Framework. The Struts Action Framework is the new name

Chapter 8 Advanced Struts Features

© 2011 ITCourseware, LLC Rev 1.3.2 Page 163

Make changes to struts-config.xml.

a. Change the /logon action to include the parameter containing the logon method name forthe DispatchAction method selection function.

b. Add an action, /logoff, that uses the same LogonAction, but needs no form or validation,and has the same parameter as the /logon action. The processing will use the logon globalforward.

(Solution: logon/struts-config.xml)

Add tags to logon.jsp to display the ActionMessage from the logoff request. Change the formaction to include the logon method name parameter.(Solution: logon/logon.jsp)

Update welcome.jsp to include a Struts link tag to the logoff action with the appropriateparameter containing the logoff method name.(Solution: logon/welcome.jsp)

Test your Logon application by accessing http://localhost:port/LogonLabs, then logging onand off. Your instructor will tell you which port to use for your environment.