You are on page 1of 6

#40 Get More Refcarz! Visit refcardz.

com

CONTENTS INCLUDE:
n
Project Layout

Apache Tapestry 5.0


n
Configuring the Web Application
n
About Pages and Components
n
Tapestry Markup Templates
Built-in Components
By Howard M. Lewis Ship
n

n
Tapestry Annotations and more...

Configuring the Web Application, continued


ABOUT Tapestry 5
application. Maven creates an entire project structure, includ-
Tapestry 5.0 is a high-productivity, component-based, open ing a web.xml and starter pages and classes.
source user interface tier for Java EE web applications. It Additional configuration is accomplished via Tapestry’s built-
combines simple, concise page templates with minimal Java in Inversion of Control container. This takes the form of a
classes (to contain state and business logic), and embraces module class that defines services and provides configuration.
convention over configuration, dynamically locating and If an AppModule class exists in the services package
adapting to your classes. This refcard covers Tapestry 5.0, (com.wizzco.snuz.services.AppModule), it is loaded automati-
(released as version 5.0.18 in December 2008), and describes cally. Maven will create this file for you.
the structure of a Tapestry application, the format of Tapestry
markup templates, the standard components, and typical Let’s turn Tapestry’s production mode off, so that any excep-
configuration options. tions will be reported in full detail:
package com.whizzco.snuz.services;
Project Layout
import org.apache.tapestry5.ioc.*;
import org.apache.tapestry5.SymbolConstants;
The first decision on a new project is the root package name.
Tapestry will automatically locate Tapestry pages and com- public class AppModule {
public static void
ponents under the root package. Figure 1 shows a sample
contributeApplicationDefaults(MappedConfiguration<String,
www.dzone.com

project layout for a root package name of com.whizzco.snuz.


String> configuration) {
Java classes to be com- configuration.add(SymbolConstants.PRODUCTION_MODE,
src/main/java/com/wizzco/snuz
piled are stored under “false”);
pages
}
src/main/java. Additional Index.java
}
resources to be packaged services
with the compiled classes AppModule.java
SymbolConstants Field Description Default Value
src/main/resources/com/wizzco/snuz/pages
are stored under src/main/ CHARSET Output and request encoding UTF-8
Index.properties
resources.
src/main/webapp COMPRESS_WHITESPACE “true” to remove excess template true
The web application is Index.tml whitespace, “false” to leave it in

under src/main/webapp, WEB-INF PRODUCTION_MODE “true” for abbreviated exceptions, true


app.properties “false” for the full exception report
complete with a WEB-INF
web.xml SUPPORTED_LOCALES Comma separated list of locale en, it, es, de, ...
folder and a web.xml con-
Figure 1: Project layout with root pack- names. Often overridden to “en”
figuration file. age name of com.whizzco.snuz.

Follow this layout and the instructions on the Tapes-


Hot try 5 home page and you can use live class reload-
Tip ing: changes to your page classes are picked
Apache Tapestry 5

up without a restart or redeploy. tech facts at your fingertips

Get More Refcardz


Configuring the web application (They’re free!)
n Authoritative content
Tapestry’s primary configuration comes from web.xml; this is n Designed for developers
n Written by top experts
where the application’s root package is defined.
n Latest tools & technologies
Parameters and Descriptions
Method Name
a URL
open a connection to
open(method, url, async)
method = HTTP verb
(GET, POST, etc.) Hot
url = url to open, may
include querystring
asynchronous request
Tip

If you are using Maven, it can build a template project for you.
async = whether to make
as callback (similar to onclick,
assign a function object
onreadystatechange event model)
onload, etc. in browser

n Hot tips & examples


your fingertips
tech facts at

request
add a header to the HTTP
setRequestHeader
(namevalue)
send the request
send(body) as request body
body = string to be used

Enter the following all on a single line:


for the response
stop the XHR from listening
abort()
(only populated after send()
stage in lifecycle of response

n Bonus content online


readyState
is called)
after
(integer, only populated
The HTTP return code
httpStatus loaded state)
response reaches the
set after
JavaScript string (only
body of response as a
responseText reaches the interactive readyState)
response
(only
as a XML document object
body of the response
responseXML the interactive readyState)

mvn archetype:create -DarchetypeGroupId=org.apache.tapestry \


set after response reaches

n New issue every 1-2 weeks


by name
read a response header
getResponseHeader
(name)
header names
rs() Get an array of all response
getAllResponseHeade

-DarchetypeArtifactId=quickstart \
-DgroupId=com.wizzco -DartifactId=snuz Subscribe Now for FREE!
-DpackageName=com.wizzco.snuz
Refcardz.com
You can replace the parts in bold with values specific to your

DZone, Inc. | www.dzone.com


2
Apache Tapestry 5
tech facts at your fingertips

Tapestry Markup Templates, continued


About Pages and components
classpath (under src/main/resources) or directly inside the web
application (under src/main/webapp). See Figure 2. Templates
In Tapestry, each page is a specific Java class in the pages
are optional, and many components do not have a template.
package and has a page name that is based on the Java class
name. Thus com.whizzco.snuz.pages.Index is page “Index”
Tapestry is not case insensitive about file names.
and com.whizzco.snuz.pages.profile.Edit is page “profile/Edit”. Hot You must match the case of the class name to the
Tapestry is case-insensitive about page names (“In- Tip case of the template file name.
dex”, “index” and “iNdEX” are all equivalent). It is also
Note case-insensitive about property names, parameter Tapestry Namespace
names, message keys, component types, and more. Tapestry uses the namespace http://tapestry.apache.org/sche-
ma/tapestry_5_0_0.xsd for its elements and attributes, usually
Each page has a Tapestry markup template file that defines assigned the prefix “t”. A minimal, empty Tapestry page will
what components are used by the page. Some components define the namespace in its outermost (“html”) element:
also have templates and their own child components.
<html xmlns:t=”http://tapestry.apache.org/schema/tapes-
Every component has try_5_0_0.xsd”>
Index
a type and an id. The </html>
type identifies what
Any elements that are not in the Tapestry namespace will
Java class will be
layout form textfield ultimately be sent to the client web browser as-is. Markup
instantiated. The id is
templates may contain other namespaces as well; these too
unique to the compo-
are sent to the client web browser as-is.
nent’s container (the
loop pagelink
page, or containing Using Expansions
component). Tapestry Figure 2: Pages contain components; some Expansions allow you to read properties of the corresponding
components contain other components.
assigns an id if you page (or component). Expansions start with a ‘${‘ sequence
don’t. and end with a ‘}’. They may appear in ordinary text, includ-
ing inside attribute values:
Pages are not like servlets; they are not singletons. There will
be many instances of each page. A page instance is only vis- <dt>Account Balance:</dt>
ible to one request at a time, and Tapestry uses a page pool <dd class=”${balanceClass}”>${balance}</dd>”
to store page instances between requests.
Expansions are not allowed inside element names or
Component classes Index Note attribute names; just inside blocks of text or inside
may extend from attribute values.
other component value = prop:activeProfile.lastName
classes (but not from Expansions are just like parameter bindings: you
other non-component
textfield Parameter Binding Hot can use a prefix. Often the message: binding prefix
classes). There is no Tip is used to access a localized message from the
required base compo- page’s message catalog.
Index
nent class in Tapestry;
activeProfile : Profile Profile
most components Adding Components
firstName : String
extend from Object. TextField lastName: String
A Tapestry component appears in the template as an element
email: String
value : Object
A page binds the
address : String
city: String
inside the Tapestry namespace.
state: String
parameters of its child zip: String
<t:textfield value=”activeProfile.lastName”/>
components. For Figure 3: Parameter Bindings read and update
<t:pagelink page=”index”>back to home page</t:pagelink>
example, a TextField properties
component’s value parameter is bound to a property, or The element name is the component type, and matches a
property expression, indicating what object property it will component class. Tapestry searches the application’s compo-
read (when rendering) or update (when the containing form is nents package first, then the built-in core library if not found.
submitted). In Figure 3, the value parameter is bound to the
Component parameters are bound using attributes of the
Index page’s activeProfile.lastName property.
element.
The prop: prefix indicates a property expression binding; this
is often the default and is usually omitted. Other binding You may assign your own id to a component with
Hot the t:id attribute. It’s always a good idea to as-
prefixes fulfill other purposes, such as accessing localized Tip sign an id to any form-related component, or to
messages from a message catalog, and are described later.
ActionLink components; your choice will be shorter and more
Tapestry Markup Templates mnemonic than what Tapestry assigns, and component ids
sometimes appear inside URLs or client-side JavaScript.
Tapestry template files are well-formed XML documents with
a .tml extension. The file name must exactly match the class Body Element
name (including case). Page templates can be stored on the The <t:body/> element is a placeholder for a component’s

DZone, Inc. | www.dzone.com


3
Apache Tapestry 5
tech facts at your fingertips

Tapestry Markup Templates, continued Built-in Components, continued


body: the portion of its container’s template enclosed by its Scaffolding Description
element. Component
BeanDisplay Displays all the properties of a JavaBean.
Component Blocks
A section of a template may be enclosed as a block: BeanEditor Creates a UI for a JavaBean, providing different types of form
controls for each property.
<t:block id=”nav”> … </t:block>
BeanEditForm Combines a BeanEditor with a Form and submit button.
Blocks may contain anything: text, elements, components or
Grid Tabular output of a set of JavaBeans, with paging and sorting.
expansions. Blocks do not render in the normal flow; instead
they can be rendered on demand (discussed in the Compo- Tapestry has built-in support for many common Ajax opera-
nent Rendering section). Blocks can be injected into a field of tions, built on top of Prototype and Scriptaculous. Many
type Block: of the components have Ajax related parameters, and the
@Inject
following table lists components that exist just for Ajax.
private Block nav; Ajax Description
Component
Block Parameters AjaxFormLoop Special looping component for use inside Forms to allow detail
Some components take a parameter of type Block. You can rows to be added or removed.
specify these using the <t:parameter> element: FormFragment A portion of a Form that can be made visible or invisible.

<t:grid source=”users”> FormInjector Allows an existing Form to be extended in place.


<t:parameter name=”empty”> Zone A receiver of dynamic content from the server; used for in=place
<p>No users match the filter.</p> updates
</t:parameter>
</t:grid>
Tapestry Annotations
Built-in Components
Tapestry uses annotations to change how fields and methods
Tapestry includes a large suite of built-in components; of your component classes are used.
essential components are described in the following tables.
Field Annotation Description
Full details of all components and component parameters are
InjectPage Injects the page that ultiately contains this component as a
available at: read-only field.
http://tapestry.apache.org/tapestry5/tapestry-core/ref/.
Parameter Defines the field as a formal parameter of the component.
Link Component Description Fields may be optional or required, may allow or forbid null,
and may have a default value.
ActionLink Triggers an “action” event on the component
Persist Identifies fields whose value should persist between requests
EventLink Triggers an arbitrary event.
(stored in the session).
PageLink Creates a link to render another page in the application.
Property Tapestry should generate a getter and setter method for the
field.
Dynamic Output Description
Component
If Renders its body if a condition is met. Tapestry resets fields to their default values after
Loop Renders its body multiple times, iterating over a collection. Hot each request. If you have data that needs to last
Output Formats and outputs an object using a Formatter. Tip longer than a single request, use the @Persist
annotation.
Form Control Component Description
Checkbox Toggle Button
Class Annotation Description
Errors Displays input validation errors for the enclosing Form.
IncludJavaScriptLibrary Ensures that the specified JavaScript libraries are linked
DateField Text field with JavaScript popup calendar to in the output markup.
Form Container of form control components. IncludeStylsheet Ensures that the specified Cascading Stylesheet file is
Label Label for related form control component. linked to in the output markup.

LinkSubmit A JavaScript-enabled link to submit a form. SuportsInformalParameters Marks the component as supporting additional, non-
formal parameters.
Palette JavaScrript multiple selection and reordering.
PasswordField Single line input field with input obscured. Method Annotation Description
Radio Exclusive toggle button. Log Tapestry should log method entry and exit (at debug level).
RadioGroup Invisible component that organizes Radio OnEvent Method is an event handler method.
components into an exclusive group.
Cached Return value of method should be cached against later
Select Drop down list. invocations.
Submit Clicking form-submit button CommitAfter The Hibernate transaction should be committed after
invoking the method.
TextArea Multiple-line text input field.
TextField Single line input field.
Many additional method annotations are discussed later, in
Tapestry’s scaffolding components allow for quick user interfac- component rendering. All those annotations have a naming
es for ordinary JavaBeans to be assembled quickly and easily. convention alternative.

DZone, Inc. | www.dzone.com


4
Apache Tapestry 5
tech facts at your fingertips

Component Events, continued


Property Expressions
Events may have a context: one or more values that are
Expressions are always evaluated in the context of a page or passed as strings in the URL. Context values are converted
component. Using the . and ?. operators allows expressions back to appropriate types and appear as method parameters
to navigate a graph of objects and properties. to event handler methods.

Expression Form Description


Naming Convention
Event handler methods are of the form “onEventName” or
true Boolean.TRUE
“onEventNameFromComponentId”. Examples:
false Boolean.False
void onSuccess() {
null null …
}
this The current page or component

1234 A number as a java.lang.Long. void onActionFromDelete() {



-1234.56 A number as a java.lang.Double. }
foo The name of a property.
@OnEvent annotation
bar() The name of a method to invoke.
The @OnEvent annotation can be used instead of the naming
foo.bar Nested property: Evaluate property foo, then property bar (can convention:
be repeated). May be used with method names.
@OnEvent(EventConstants.SUCCESS)
foo?.bar Safe dereference: Evaluate foo then bar, unless foo is null, in
which case the expression’s value is null. void storeOrderInDatabase() {

‘err’ A string literal, inside single quotes. }

Property expressions are updatable only if the final form is a @OnEvent(component=”delete”)


void deleteLineItem() {
property, and there is a setter method for that property. The …
case of property and method names is ignored. The . and ?. }
operators can be called as many times as you need.
Tip: Use the @OnEvent annotation to support more descrip-
The safe dereference operator, ?., keeps you from tive method names.
Hot having to nest multiple If components to safely
Tip access a nested property where some of the Return values
Return values from event handler methods are used for page
intermediate properties may be null.
navigation:
Type Meaning
Binding Prefixes
String Name of page to render.
Class Class of page to render.
The default binding prefix for most component parameters is
Object Page instance to render (often via @InjectPage).
prop:, meaning a property expression. In certain cases, a par-
StreamResponse Send byte stream direct to client.
ticular parameter will have a different default binding prefix,
often literal:. java.net.URL External URL to redirect to.
boolean Return true to cancel event bubbling
Essential Binding Prefixes Meaning
block: The id of a block within the template. Event bubbling
component: The id of a child component. Used to connect two When an event is triggered on a component, the first step is
components together (such as Label and TextField). to look in the component itself for an event handler method,
literal: A literal string. then its container, then its container’s container, and so forth.
message: A key from the component’s message catalog. Event bubbling occurs when there is no event handler, or an
prop: A property expression.
event handler exists but returns null (or void). The event is
re-triggered in the container. As the event bubbles, it always
appears to be from the component last checked.
Component events
Form events
The Form component fires a series of events when rendering
Tapestry interacts with your application code by reading and
and when processing a submission:
updating properties, and by invoking event handler methods.
Event handler methods may have any visibility. Component Event Name When Usage
events may be triggered by a request from the client (such as prepareForRender render Prepare page state to render
a form submission) or may exist only on the server, or some the form.
mix thereof. prepareForSubmit submit Prepare page state to process
the form submission.
Events have a name: in many cases, the event name is “ac-
prepare render/submit Prepare the page state to
tion”. Some components trigger other events (see their docu- render and submit.
mentation). Class EventConstants defines string constants for validateForm submit Perform final cross-field
all events provided as part of Tapestry. validations after all fields have
processed.

DZone, Inc. | www.dzone.com


5
Apache Tapestry 5
tech facts at your fingertips

Component Events, continued Component Rendering, continued


success submit Invoked if no input field advances to the next phase.
validation errors.
If a component has a template, it is rendered after the
failure submit Invoked if there are input field
validation errors. BeginRender phase. The template may include a <t:body/>
submit submit Invoked last, regardless of
element to render the component’s body. A component
validation errors. without a template is treated as if its template consists of just
a <t:body/> element.
Component Rendering
Component life cycle
Tapestry breaks the render- Start Components, as part of pages, have a specific life cycle.
ing of a component down Components are instantiated and added to pages and
into phases, shown in Figure containing components. Once the page is fully constructed,
4. Each phase corresponds SetupRender false
components receive a one-time notification that the page
to a method of the com- true has loaded. For the duration of a request, a page is attached
ponent class (possibly a to the request: there is a notification for the page being at-
method inherited from a BeginRender false
tached and later, for the page being detached (before it is
base class). The method true returned to the page pool).
names match render phase
names (case insensitive). Render Template There are three method annotations for this purpose: @Page-
Alternately, you may attach Loaded, @PageAttached and @PageDetached. Alternately, you
a @SetupRender, @Begin- can also use the method naming convention: pageLoaded(),
Render Body
Render, etc. annotation to a pageAttached() and pageDetached().
method.
false AfterRender
Localization
Normally, each phase fol- true
lows the previous (the bold Tapestry localization support is pervasive. Tapestry deter-
lines marked “true”). A false CleanupRender mines the client’s desired locale based on standard HTTP
render phase method may headers, or the presence of a HTTP Cookie.
true
return false to jump back-
wards (the dotted lines). Pages and components may have their own individual mes-
End

This is how conditional sage catalogs.


components (such as If) and Figure 4: Component Rendering A message catalog is a set of files with similar names: My-
Phases
looping components (such Component.properties for the default message catalog, or
as Loop and Grid) operate. with locale names appended: MyComponent_fr.properties or
MyComponent_de.properties.
Render phase methods may be any visibility. They may either
take no parameters, or take a parameter of type MarkupWriter. Component subclasses may have message catalogs; subclass
The MarkupWriter.element() method is used to create a new keys override super-class keys.
output element (along with attributes) and should always be
Applications may have a message catalog: WEB-INF/app.prop-
balanced by a call to MarkupWriter.end().
erties. Page and component message keys override applica-
Components will often start an element in the BeginRender tion messages keys.
phase, and end it in the AfterRender phase.
Messages are accessible inside templates:
Components that support informal parameters should be ${message:greeting}, ${user.firstName}!
marked with the @SupportsInformalParameters class annota-
You may inject your component’s message catalog as a Mes-
tion, and include a call to ComponentResources.renderInformal-
sages object:
Parameters():
@Inject
@Inject
private Messages messages;
private ComponentResources resources;

void beginRender(MarkupWriter writer) { Using the @Inject annotation on a field of type java.util.Locale
writer.element(“div”, “class”, “popup”); will inject the page’s locale. This can be used to format dates
resources.renderInformalParameters(writer); and currency values.
}

void afterRender(MarkupWriter writer) { Environmental Objects


writer.end();
} Environmental objects are request-scoped objects that are
of use to your components. The @Environmental annotation
A render phase method may also return a component instance dynamically binds a component field to an environmental
or a Block instance; the component or Block will take over object. Environmental objects don’t have a name; the type of
and be rendered completely before the current component the Environmental is used to locate the object.

DZone, Inc. | www.dzone.com


6
Apache Tapestry 5
tech facts at your fingertips

Environmental Objects, continued Tapestry Services, continued


Environmental Type Usage BeanModelSource Source for BeandEditor that can be customized and
provided to Grid and BeandEditor components.
FormSupport Details about the current form render, or form
submission. Generation of unique control names within ComponentSource Provides access to pages or components.
the form.
Request Current request object, used to obtain parameter
RenderSupport Generation of unique element ids, and inclusion of values directly.
JavaScript libraries and initialization snippets.
For More Information
Tapestry 5 Home Page:
Tapestry Services
http://tapestry.apache.org/tapestry5/

Tapestry includes a number of useful services that can be Detailed component reference (with examples):
injected into components or other services. Other services http://tapestry.apache.org/tapestry5/tapestry-core/ref/
are useful not for injection, but to be configured. Tapestry Wiki:
Service Description http://wiki.apache.org/tapestry/
ApplicationDefaults Configuration overrides FactoryDefaults symbols used
to configure other services.

A B O U T T HE A U T H O R REC O MMEN D E D B O O K
Howard M. Lewis Ship Tapestry in Action
Howard M. Lewis Ship is the creator of the Apache The definitive guide to the Tapestry ap-
Tapestry project. He is a frequent speaker at JavaOne, proach: creating full-featured web apps by
ApacheCon, No Fluff Just Stuff, and other software connecting framework components to eco-
conferences. He is the author of “Tapestry in Action” nomical amounts of application code. Many
for Manning Publications, which covers Tapestry 3. He simple examples show you how to tackle
has trained dozens of developers in Tapestry over the common tasks such as form validation, ap-
last five years, is currently the Director of Open Source plication localization, client-side scripting,
Technology at Formos, a Vancouver, Washington based and synchronization between browser and app server.
consulting company.
Web site BUY NOW
http://howardlewisship.com books.dzone.com/books/tapestryinaction
http://www.formos.com

Get More FREE Refcardz. Visit refcardz.com now!


Upcoming Refcardz: Available:
Core Seam Essential Ruby Core CSS: Part I

Core CSS: Part III Essential MySQL Struts2


JUnit and EasyMock Core .NET
Hibernate Search Very First Steps in Flex
Getting Started with MyEclipse
FREE
Equinox Spring Annotations C#
Core Java Groovy
EMF
Core CSS: Part II NetBeans IDE 6.1 Java Editor
XML
PHP RSS and Atom
JSP Expression Language Getting Started with JPA GlassFish Application Server
ALM Best Practices JavaServer Faces Silverlight 2 Design Patterns
Published June 2008
HTML and XHTML Visit refcardz.com for a complete listing of available Refcardz.

DZone, Inc. ISBN-13: 978-1-934238-43-1


1251 NW Maynard ISBN-10: 1-934238-43-0
Cary, NC 27513 50795
888.678.0399
DZone communities deliver over 4 million pages each month to 919.678.0300

more than 1.7 million software developers, architects and decision Refcardz Feedback Welcome
refcardz@dzone.com
$7.95

makers. DZone offers something for everyone, including news,


tutorials, cheatsheets, blogs, feature articles, source code and more. Sponsorship Opportunities 9 781934 238431
sales@dzone.com
“DZone is a developer’s dream,” says PC Magazine.
Copyright © 2009 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical,
photocopying, or otherwise, without prior written permission of the publisher. Reference: Tapestry in Action, Howard M. Lewis Ship, Manning Publishing Co. 2004. Version 1.0

You might also like