为了正常的体验网站,请在浏览器设置里面开启Javascript功能!

Tapestry 5.0

2013-07-22 6页 pdf 1MB 16阅读

用户头像

is_760418

暂无简介

举报
Tapestry 5.0 DZone, Inc. | www.dzone.com Apache Tapestry 5.0 ABOUT TApesTry 5 Tapestry 5.0 is a high-productivity, component-based, open source user interface tier for Java EE web applications. It combines simple, concise page templates with minimal Java classes (to ...
Tapestry 5.0
DZone, Inc. | www.dzone.com Apache Tapestry 5.0 ABOUT TApesTry 5 Tapestry 5.0 is a high-productivity, component-based, open source user interface tier for Java EE web applications. It combines simple, concise page templates with minimal Java classes (to contain state and business logic), and embraces convention over configuration, dynamically locating and adapting to your classes. This refcard covers Tapestry 5.0, (released as version 5.0.18 in December 2008), and describes the structure of a Tapestry application, the format of Tapestry markup templates, the standard components, and typical configuration options. n Authoritative content n Designed for developers n Written by top experts n Latest tools & technologies n Hot tips & examples n Bonus content online n New issue every 1-2 weeks Subscribe Now for FREE! Refcardz.com Get More Refcardz (They’re free!) tech facts at your finger tips Method Name Parameters and Descript ions open(method, url, async) open a connection to a UR L method = HTTP verb (GET , POST, etc.) url = url to open, may incl ude querystring async = whether to make asynchronous request onreadystatechange assign a function object as c allback (similar to onclick, onload, etc. in browser even t model) setRequestHeader (namevalue) add a header to the HTTP request send(body) send the request body = string to be used a s request body abort() stop the XHR from listenin g for the response readyState stage in lifecycle of respons e (only populated after sen d() is called) httpStatus The HTTP return code (int eger, only populated after response reaches the load ed state) responseText body of response as a Jav aScript string (only set aft er response reaches the inte ractive readyState) responseXML body of the response as a XML document object (on ly set after response reaches the interactive readyState ) getResponseHeader (name) read a response header b y name getAllResponseHeaders() Get an array of all respon se header names Hot Tip tech facts at your fingertips prOjecT LAyOUT The first decision on a new project is the root package name. Tapestry will automatically locate Tapestry pages and com- ponents under the root package. Figure 1 shows a sample project layout for a root package name of com.whizzco.snuz. A p ac h e T ap e st ry 5 w w w .d zo n e. co m G e t M o re R e fc ar z! V is it r ef ca rd z. co m #40 By Howard M. Lewis Ship Configuring the Web Application, continued Java classes to be com- piled are stored under src/main/java. Additional resources to be packaged with the compiled classes are stored under src/main/ resources. The web application is under src/main/webapp, complete with a WEB-INF folder and a web.xml con- figuration file. cOnfigUring The weB AppLicATiOn Follow this layout and the instructions on the Tapes- try 5 home page and you can use live class reload- ing: changes to your page classes are picked up without a restart or redeploy. Hot Tip Tapestry’s primary configuration comes from web.xml; this is where the application’s root package is defined. If you are using Maven, it can build a template project for you. Enter the following all on a single line: mvn archetype:create -DarchetypeGroupId=org.apache.tapestry \ -DarchetypeArtifactId=quickstart \ -DgroupId=com.wizzco -DartifactId=snuz -DpackageName=com.wizzco.snuz You can replace the parts in bold with values specific to your application. Maven creates an entire project structure, includ- ing a web.xml and starter pages and classes. Additional configuration is accomplished via Tapestry’s built- in Inversion of Control container. This takes the form of a module class that defines services and provides configuration. If an AppModule class exists in the services package (com.wizzco.snuz.services.AppModule), it is loaded automati- cally. Maven will create this file for you. Let’s turn Tapestry’s production mode off, so that any excep- tions will be reported in full detail: package com.whizzco.snuz.services; import org.apache.tapestry5.ioc.*; import org.apache.tapestry5.SymbolConstants; public class AppModule { public static void contributeApplicationDefaults(MappedConfiguration configuration) { configuration.add(SymbolConstants.PRODUCTION_MODE, “false”); } } SymbolConstants Field Description Default Value CHARSET Output and request encoding UTF-8 COMPRESS_WHITESPACE “true” to remove excess template whitespace, “false” to leave it in true PRODUCTION_MODE “true” for abbreviated exceptions, “false” for the full exception report true SUPPORTED_LOCALES Comma separated list of locale names. Often overridden to “en” en, it, es, de, ... Figure 1: Project layout with root pack- age name of com.whizzco.snuz. cOnTenTs incLUDe: n Project Layout n Configuring the Web Application n About Pages and Components n Tapestry Markup Templates n Built-in Components n Tapestry Annotations and more... src/main/java/com/wizzco/snuz pages Index.java services AppModule.java src/main/resources/com/wizzco/snuz/pages Index.properties src/main/webapp Index.tml WEB-INF app.properties web.xml tech facts at your fingertips DZone, Inc. | www.dzone.com ABOUT pAges AnD cOmpOnenTs In Tapestry, each page is a specific Java class in the pages package and has a page name that is based on the Java class name. Thus com.whizzco.snuz.pages.Index is page “Index” and com.whizzco.snuz.pages.profile.Edit is page “profile/Edit”. Each page has a Tapestry markup template file that defines what components are used by the page. Some components also have templates and their own child components. Every component has a type and an id. The type identifies what Java class will be instantiated. The id is unique to the compo- nent’s container (the page, or containing component). Tapestry assigns an id if you don’t. Pages are not like servlets; they are not singletons. There will be many instances of each page. A page instance is only vis- ible to one request at a time, and Tapestry uses a page pool to store page instances between requests. Component classes may extend from other component classes (but not from other non-component classes). There is no required base compo- nent class in Tapestry; most components extend from Object. A page binds the parameters of its child components. For example, a TextField component’s value parameter is bound to a property, or property expression, indicating what object property it will read (when rendering) or update (when the containing form is submitted). In Figure 3, the value parameter is bound to the Index page’s activeProfile.lastName property. The prop: prefix indicates a property expression binding; this is often the default and is usually omitted. Other binding prefixes fulfill other purposes, such as accessing localized messages from a message catalog, and are described later. 2 Apache Tapestry 5 TApesTry mArkUp TempLATes Tapestry template files are well-formed XML documents with a .tml extension. The file name must exactly match the class name (including case). Page templates can be stored on the Index formlayout pagelink textfield loop Figure 2: Pages contain components; some components contain other components. Index textfield Profile firstName : String lastName: String email: String address : String city: String state: String zip: String Index activeProfile : Profile value = prop:activeProfile.lastName Parameter Binding TextField value : Object Figure 3: Parameter Bindings read and update properties Tapestry is not case insensitive about file names. You must match the case of the class name to the case of the template file name. Hot Tip Tapestry Namespace Tapestry uses the namespace http://tapestry.apache.org/sche- ma/tapestry_5_0_0.xsd for its elements and attributes, usually assigned the prefix “t”. A minimal, empty Tapestry page will define the namespace in its outermost (“html”) element: Any elements that are not in the Tapestry namespace will ultimately be sent to the client web browser as-is. Markup templates may contain other namespaces as well; these too are sent to the client web browser as-is. Using Expansions Expansions allow you to read properties of the corresponding page (or component). Expansions start with a ‘${‘ sequence and end with a ‘}’. They may appear in ordinary text, includ- ing inside attribute values:
Account Balance:
${balance}
” Expansions are just like parameter bindings: you can use a prefix. Often the message: binding prefix is used to access a localized message from the page’s message catalog. Hot Tip Adding Components A Tapestry component appears in the template as an element inside the Tapestry namespace. back to home page The element name is the component type, and matches a component class. Tapestry searches the application’s compo- nents package first, then the built-in core library if not found. Component parameters are bound using attributes of the element. classpath (under src/main/resources) or directly inside the web application (under src/main/webapp). See Figure 2. Templates are optional, and many components do not have a template. Tapestry Markup Templates, continued You may assign your own id to a component with the t:id attribute. It’s always a good idea to as- sign an id to any form-related component, or to ActionLink components; your choice will be shorter and more mnemonic than what Tapestry assigns, and component ids sometimes appear inside URLs or client-side JavaScript. Hot Tip Body Element The element is a placeholder for a component’s Expansions are not allowed inside element names or attribute names; just inside blocks of text or inside attribute values. Note Tapestry is case-insensitive about page names (“In- dex”, “index” and “iNdEX” are all equivalent). It is also case-insensitive about property names, parameter names, message keys, component types, and more. Note tech facts at your fingertips DZone, Inc. | www.dzone.com Tapestry Markup Templates, continued Built-in Components, continued 3 Apache Tapestry 5 BUiLT-in cOmpOnenTs Link Component Description ActionLink Triggers an “action” event on the component EventLink Triggers an arbitrary event. PageLink Creates a link to render another page in the application. Dynamic Output Component Description If Renders its body if a condition is met. Loop Renders its body multiple times, iterating over a collection. Output Formats and outputs an object using a Formatter. Form Control Component Description Checkbox Toggle Button Errors Displays input validation errors for the enclosing Form. DateField Text field with JavaScript popup calendar Form Container of form control components. Label Label for related form control component. LinkSubmit A JavaScript-enabled link to submit a form. Palette JavaScrript multiple selection and reordering. PasswordField Single line input field with input obscured. Radio Exclusive toggle button. RadioGroup Invisible component that organizes Radio components into an exclusive group. Select Drop down list. Submit Clicking form-submit button TextArea Multiple-line text input field. TextField Single line input field. Tapestry’s scaffolding components allow for quick user interfac- es for ordinary JavaBeans to be assembled quickly and easily. Scaffolding Component Description BeanDisplay Displays all the properties of a JavaBean. BeanEditor Creates a UI for a JavaBean, providing different types of form controls for each property. BeanEditForm Combines a BeanEditor with a Form and submit button. Grid Tabular output of a set of JavaBeans, with paging and sorting. body: the portion of its container’s template enclosed by its element. Component Blocks A section of a template may be enclosed as a block: Blocks may contain anything: text, elements, components or expansions. Blocks do not render in the normal flow; instead they can be rendered on demand (discussed in the Compo- nent Rendering section). Blocks can be injected into a field of type Block: @Inject private Block nav; Block Parameters Some components take a parameter of type Block. You can specify these using the element:

No users match the filter.

Tapestry has built-in support for many common Ajax opera- tions, built on top of Prototype and Scriptaculous. Many of the components have Ajax related parameters, and the following table lists components that exist just for Ajax. Ajax Component Description AjaxFormLoop Special looping component for use inside Forms to allow detail rows to be added or removed. FormFragment A portion of a Form that can be made visible or invisible. FormInjector Allows an existing Form to be extended in place. Zone A receiver of dynamic content from the server; used for in=place updates TApesTry AnnOTATiOns Tapestry uses annotations to change how fields and methods of your component classes are used. Field Annotation Description InjectPage Injects the page that ultiately contains this component as a read-only field. Parameter Defines the field as a formal parameter of the component. Fields may be optional or required, may allow or forbid null, and may have a default value. Persist Identifies fields whose value should persist between requests (stored in the session). Property Tapestry should generate a getter and setter method for the field. Tapestry resets fields to their default values after each request. If you have data that needs to last longer than a single request, use the @Persist annotation. Hot Tip Class Annotation Description IncludJavaScriptLibrary Ensures that the specified JavaScript libraries are linked to in the output markup. IncludeStylsheet Ensures that the specified Cascading Stylesheet file is linked to in the output markup. SuportsInformalParameters Marks the component as supporting additional, non- formal parameters. Method Annotation Description Log Tapestry should log method entry and exit (at debug level). OnEvent Method is an event handler method. Cached Return value of method should be cached against later invocations. CommitAfter The Hibernate transaction should be committed after invoking the method. Many additional method annotations are discussed later, in component rendering. All those annotations have a naming convention alternative. Tapestry includes a large suite of built-in components; essential components are described in the following tables. Full details of all components and component parameters are available at: http://tapestry.apache.org/tapestry5/tapestry-core/ref/. tech facts at your fingertips DZone, Inc. | www.dzone.com 4 Apache Tapestry 5 prOperTy expressiOns Expressions are always evaluated in the context of a page or component. Using the . and ?. operators allows expressions to navigate a graph of objects and properties. Expression Form Description true Boolean.TRUE false Boolean.False null null this The current page or component 1234 A number as a java.lang.Long. -1234.56 A number as a java.lang.Double. foo The name of a property. bar() The name of a method to invoke. foo.bar Nested property: Evaluate property foo, then property bar (can be repeated). May be used with method names. foo?.bar Safe dereference: Evaluate foo then bar, unless foo is null, in which case the expression’s value is null. ‘err’ A string literal, inside single quotes. Property expressions are updatable only if the final form is a 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. Hot Tip The safe dereference operator, ?., keeps you from having to nest multiple If components to safely access a nested property where some of the intermediate properties may be null. BinDing prefixes The default binding prefix for most component parameters is prop:, meaning a property expression. In certain cases, a par- ticular parameter will have a different default binding prefix, often literal:. Essential Binding Prefixes Meaning block: The id of a block within the template. component: The id of a child component. Used to connect two components together (such as Label and TextField). literal: A literal string. message: A key from the component’s message catalog. prop: A property expression. cOmpOnenT evenTs Tapestry interacts with your application code by reading and updating properties, and by invoking event handler methods. Event handler methods may have any visibility. Component events may be triggered by a request from the client (such as a form submission) or may exist only on the server, or some mix thereof. Events have a name: in many cases, the event name is “ac- tion”. Some components trigger other events (see their docu- mentation). Class EventConstants defines string constants for all events provided as part of Tapestry. Type Meaning String Name of page to render. Class Class of page to render. Object Page instance to render (often via @InjectPage). StreamResponse Send byte stream direct to client. java.net.URL External URL to redirect to. boolean Return true to cancel event bubbling Event bubbling When an event is triggered on a component, the first step is to look in the component itself for an event handler method, then its container, then its container’s container, and so forth. Event bubbling occurs when there is no event handler, or an 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. Form events The Form component fires a series of events when rendering and when processing a submission: Events may have a context: one or more values that are passed as strings in the URL. Context values are converted back to appropriate types and appear as method parameters to event handler methods. Naming Convention Event handler methods are of the form “onEventName” or “onEventNameFromComponentId”. Examples: void onSuccess() { … } void onActionFromDelete() { … } @OnEvent annotation The @OnEvent annotation can be used instead of the naming convention: @OnEvent(EventConstants.SUCCESS) void storeOrderInDatabase() { … } @OnEvent(component=”delete”) void deleteLineItem() { … } Tip: Use the @OnEvent annotation to support more descrip- tive method names. Return values Return values from event handler methods are used for page navigation: Component Events, continued Event Name When Usage prepareForRender render Prepare page state to render the form. prepareForSubmit submit Prepare page state to process the form submission. prepare render/submit Prepare the page state to render and submit. validateForm submit Perform final cross-field validations after all fields have processed. tech facts at your fingertips DZone, Inc. | www.dzone.com 5 Apache Tapestry 5 cOmpOnenT renDering Component Events, continued Tapestry breaks the render- ing of a component down into phases, shown in Figure 4. Each phase corresponds to a method of the com- ponent class (possibly a method inheri
/
本文档为【Tapestry 5.0】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。 本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。 网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。

历史搜索

    清空历史搜索