Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning Apache Struts - From Novice To Professional (2006)

.pdf
Скачиваний:
60
Добавлен:
17.08.2013
Размер:
11.68 Mб
Скачать

378

A P P E N D I X B C O M M O N L Y U S E D C L A S S E S

execute() function. Actions must be programmed in a thread-safe manner, because Struts will share the same instance for multiple simultaneous requests. This means you should design with the following points in mind:

Instance and static variables must not be used to store information related to the state of a particular request.

They may be used to share global resources across requests for the same Action.

Access to other resources (JavaBeans, session variables, etc.) must be synchronized if those resources require protection. (Generally, however, resource classes should be designed to provide their own protection where necessary.)

Return Type

Function

Comments

ActionForward

execute(ActionMapping mapping,

 

ActionForm form,

 

HttpServletRequest request,

 

HttpServletResponse response)

Processes the specified HTTP request, and creates the corresponding HTTP response (or forward to another web component that will create it), with provision for handling exceptions thrown by the business logic

void

addErrors(HttpServletRequest request,

 

ActionMessages errors)

Adds the specified errors keys into the appropriate request attribute for use by the <html:errors> tag, if any messages are required

void

saveErrors(HttpServletRequest request,

 

ActionMessages errors)

Saves the specified error messages keys into the appropriate request attribute for use by the

<html:errors> tag, if any messages are required

org.apache.struts.action.ActionForm

An ActionForm is a JavaBean optionally associated with one or more ActionMappings. Such a bean will have had its properties initialized from the corresponding request parameters before the corresponding Action.execute() function is called.

A P P E N D I X B C O M M O N L Y U S E D C L A S S E S

379

When the properties of this bean have been populated, but before the execute() function of the Action is called, this bean’s validate() function will be called, which gives the bean a chance to verify that the properties submitted by the user are correct and valid. If this function finds problems, it returns an error messages object that encapsulates those problems, and Struts will return control to the corresponding input form. Otherwise, the validate() function returns null, indicating that everything is acceptable and the corresponding Action.execute() function should be called.

The ActionForm class must be subclassed in order to be instantiated.

Subclasses should provide property getter and setter methods for all of the bean properties they wish to expose. In addition, they should override any of the public or protected methods for which they wish to provide modified functionality.

Because ActionForms are JavaBeans, subclasses should also implement Serializable, as required by the JavaBean specification. Some containers require that an object meet all JavaBean requirements in order to use the introspection API upon which ActionForms rely.

Return Type

Function

Comments

void

reset(ActionMapping mapping,

 

HttpServletRequest

request)

ActionErrors

validate(ActionMapping mapping,

 

HttpServletRequest

request)

Resets bean properties to their default state, as needed

Validates the properties that have been set for this HTTP request, and returns an ActionErrors object that encapsulates any validation errors that have been found

org.apache.struts.upload.FormFile

This interface is used to represent a file uploaded by a client.

Return Type

Function

Comments

void

destroy()

Destroys all content for this form file

String

getContentType()

Gets the content type string for this file

byte[]

getFileData()

Gets the data in byte array for this file

String

getFileName()

Gets the filename of this file

int

getFileSize()

Gets the size of this file

InputStream

getInputStream()

Gets an InputStream that represents this file

 

 

 

380

A P P E N D I X B C O M M O N L Y U S E D C L A S S E S

org.apache.struts.tiles.ComponentContext

This class is the equivalent of HttpServletRequest for a Tile.

Return Type

Function

Comments

void

addAll(Map newAttributes)

Adds all attributes to this context

void

addMissing(Map defaultAttrs)

Adds all missing attributes to

 

 

this context

Object

getAttribute(String name)

Gets an attribute from

 

 

this context

Iterator

getAttributeNames()

Gets the names of all attributes

void

putAttribute(String name,Object value)

Puts a new attribute into

 

 

the context

 

 

 

org.apache.struts.action.ExceptionHandler

An ExceptionHandler is a special class to handle exceptions generated in your ActionForm or Action subclasses. Refer to Chapter 9 on how to declare and use ExceptionHandlers.

Return Type

Function

Comments

ActionForward

execute(Exception ex, ExceptionConfig ae,

 

ActionMapping mapping, ActionForm form,

 

HttpServletRequest request,

 

HttpServletResponse response)

Handles the Exception. Your subclasses must override this function.

A P P E N D I X C

■ ■ ■

Struts Tag Reference

This appendix is a reference on all Struts 1.2 tags, from the five tag libraries: HTML, Bean, Logic, Nested, and Tiles. We’ve included usage examples and information on Struts-EL and JSTL (see Chapter 10 for both), as well as JSF and Struts-Faces Integration Library (see Chapter 20 for both) equivalent tags where appropriate. This reference does not include the obsolete Template tag library, which has been superseded by the Tiles tag library.

To make this reference more compact, we’ve collected attributes that occur in more than one tag under one or more common attribute sets. These are introduced at the start of each section describing a tag library.

The HTML Tag Library

The custom tags in the HTML library are essentially in one-to-one relationship to the ordinary HTML <form> tag and its associated input tags, like the various <input> tags.

The purpose of this tag library is to enable you to connect the View tier to the Controller tier of your Struts webapp. The linkage between the two is done statically in struts-config.xml.

The tags in the HTML library can be divided into four groups based on function:

Form tags: These tags transfer data from View to Controller. The tags are mostly in one-to-one correspondence with their HTML equivalents (<form> and the various HTML data input tags), but there are extra Struts-specific tags (e.g., multibox) that do much more to facilitate the easy transfer of data between View and Controller.

Message tags: These tags display (in the View tier) messages that originate from the Controller.

URL tags: These tags are counterparts to ordinary HTML tags that require a URL to function. The Struts versions exist primarily to allow you to use the names of global forwards instead of actual URLs.

Miscellaneous tags: These tags have no clear functional grouping and have to be treated individually.

381

382

A P P E N D I X C S T R U T S T A G R E F E R E N C E

Tables C-1 to C-4 give a synopsis of these tags by their functional grouping. Tables C-1 to C-4 are based on the Apache documentation for those tags. A copy of the Apache License is available at www.apache.org/licenses/LICENSE-2.0.

Table C-1. Form Tags of the HTML Tag Library

Tag

Usage

form

Defines a form.

checkbox

Generates a checkbox input field.

file

Generates a file selection input field.

hidden

Generates a hidden field.

multibox

Generates multiple checkbox input fields.

radio

Generates a radio button input field.

select and option, options,

select generates a drop-down list. The option elements are

or optionsCollection

nested within select, and generate the options for the enclosing

 

select element.

text/password

Generates a text/password input field.

textarea

Generates an HTML textarea input field.

image

Generates an image input field.

button

Generates a button input field.

cancel

Generates a cancel button.

submit

Generates a submit button.

reset

Generates a reset button.

 

 

Table C-2. Message Tags of the HTML Tag Library

Tag

Usage

errors

Displays error messages

messages

Iterates through error messages and messages (refer to the entry for <logic:iterate>

 

for a description of these terms)

 

 

A P P E N D I X C S T R U T S T A G R E F E R E N C E

383

Table C-3. URL Tags of the HTML Tag Library

Tag

Usage

base

Generates an HTML <base> tag. This creates a reference from which all relative

 

paths in your JSP will be calculated.

img

Generates an HTML <img> tag.

link

Generates an HTML hyperlink.

rewrite

Expands a given URI. Useful in creating URLs for input into your JavaScript functions.

 

Table C-4. Miscellaneous Tags of the HTML Tag Library

 

 

Tag

Usage

 

 

html

Generates an <html> tag. Also includes language attributes from the user’s session.

xhtml

Tells other tags on the page to render themselves as XHTML 1.0–conformant tags.

frame

Generates an HTML frame.

javascript

Indicates the placement of autogenerated JavaScript. Used in conjunction with

 

the Validator framework, described in Chapter 15.

 

 

Common Attribute Sets

There are attributes that are common to more than one tag of the HTML library. These may be naturally grouped into few common attribute sets, which we’ll describe next. We’ll give each set an abbreviation, which we’ll use in subsequent descriptions of each tag.

The Event Handler Attribute Set

The biggest such attribute set consists of attributes corresponding to HTML event handler attributes. The Struts versions are exactly the same as the HTML versions. Let’s refer to these as the Event Handler attribute set, or evt-attrs for short. The attributes in this set are described in Table C-5. The value of each attribute in this set is a JavaScript function that is called when a particular action occurs (e.g., mouse clicks, loss of focus, etc.). If you’re familiar with HTML, Table C-5 should hold no surprises for you.

384 A P P E N D I X C S T R U T S T A G R E F E R E N C E

Table C-5. The evt-attrs Attribute Set

Attribute Name

Trigger

onblur

Element loses focus.

onchange

Element’s value changed and element has lost focus.

onclick

Element is clicked.

ondblclick

Element is double-clicked.

onfocus

Element gains focus.

onkeydown

Key pressed when element has focus.

onkeypress

Key pressed then released when element has focus.

onkeyup

Key released when element has focus.

onmousedown

Mouse button is pressed while pointer is over element.

onmousemove

Mouse pointer is moved over element.

onmouseout

Mouse pointer leaves element.

onmouseover

Mouse pointer enters element.

onmouseup

Mouse button is released while pointer is over element.

 

 

The Accessibility Attribute Set

The next set is also HTML related, and these attributes aid in accessibility.

Table C-6 lists these tags, which we’ll refer to as the Accessibility attribute set, or acc-attrs for short.

Table C-6. The acc-attrs Attribute Set

Attribute Name

Usage

accesskey

Specifies the key that if pressed, causes this element to gain focus.

alt

Specifies the alternate text for this element.

altKey

Specifies the message resource key for the alternate text.

tabindex

A positive integer that specifies the tab order for this element.

title

Specifies the advisory title for this element. In most graphical browsers,

 

the advisory title appears as a tooltip when the mouse pointer goes over

 

the element.

titleKey

Specifies the message resource key for the advisory title.

 

 

Most attributes in Table C-6 are simply mirror images of their HTML counterparts. The exceptions are altKey and titleKey, which use Struts’ message resource file to produce a localized version of the actual attribute (alt and title, respectively).

A P P E N D I X C S T R U T S T A G R E F E R E N C E

385

The Rendering Attribute Set

The Rendering attribute set (ren-attrs) consists of attributes that specify the final rendering of the underlying HTML elements that correspond to a tag. These are listed in Table C-7.

Table C-7. The ren-attrs Attribute Set

Attribute Name

Usage

disabled

This boolean attribute disables (disabled = "true") an input element. In

 

most graphical browsers, this causes the HTML element to be grayed out.

style

Specifies the CSS styles for this element.

styleClass

Specifies the CSS stylesheet class for this element. styleClass corresponds

 

to the class HTML attribute.

styleId

Specifies the HTML ID to be assigned to this element. That is, styleId

 

corresponds to the id HTML attribute.

 

 

The Struts Attribute Set

The Struts attribute set (struts-attrs) consists of commonly used attributes specific to Struts. These are listed in Table C-8.

Table C-8. The struts-attrs Attribute Set

Attribute Name

Usage

bundle

Specifies the message resources bundle to use. If this isn’t specified, the

 

default Application.properties file is used. Bundles are a way for you to

 

use multiple message resource files in your webapp. Note that the current

 

support for this feature is uneven. Also, using it complicates maintenance.

 

The bundle attribute is explained in more detail in the entry for

 

<bean:message>. This attribute was newly introduced with Struts 1.2.5.

indexed

This boolean attribute is valid only when the enclosing tag is nested in-

 

side the <logic:iterate> tag. If true, the name of the rendered HTML tag

 

will be indexed, for example, myProperty[12]. The number in brackets will

 

be incremented for every iteration of the enclosing <logic:iterate> tag.

property

The name of the request parameter or HTML POST element that will be

 

used when a form is submitted, set to the specified value (see the next entry).

value

Value of the input element. This value is submitted to the Controller tier,

 

either in the request parameter or in the HTML POST itself.

 

 

The Initial Bean Attribute Set

The Initial Bean attribute set (init-attr) consists of just one attribute, name, which refers to a JavaBean whose corresponding property (specified by the property attribute of the element) is used as an initial value for the rendered element. The form bean associated with the enclosing form is the default bean for this task, and it is used if name is not specified.

386

A P P E N D I X C S T R U T S T A G R E F E R E N C E

The Error Style Attribute Set (Struts 1.2.5+)

The Error Style attribute set (err-attrs) was newly introduced with Struts 1.2.5. These attributes enable you to specify an error style if a given input element hits a validation error. Table C-9 describes these attributes.

Table C-9. The err-attrs Attribute Set

Attribute Name

Usage

errorKey

The key under which the error messages are stored. You only need to

 

specify this attribute if you also specified the associated <html:errors>’s

 

name attribute. The two must be the same.

errorStyle

The CSS style for the element if there is an error message for it.

errorStyleClass

The name of the CSS style class for the element if there is an error

 

message for it.

errorStyleId

Assigns this new ID to the element, if there is an error message for it.

 

 

Struts-EL Tags for the HTML Tag Library

All tags in the HTML library have EL-enabled versions.

Note EL-enabled tags are those that allow you to use EL expressions. Refer to Chapter 10 for examples.

base

This tag is used to allow you to conveniently create an HTML <base> tag.

The HTML <base> tag allows you to specify the base URL from which to calculate relative paths (e.g., ../../myscripts.js or mypage.html) in your JSPs. You might think that such URLs are resolved using the absolute path of the enclosing JSP page, but this isn’t necessarily the case. The only way to guarantee this is to use the <base> tag, or much more conveniently, <html:base>.

Usage Restrictions

Both <base> and <html:base> must be a child tag of HTML’s <head> tag.

A P P E N D I X C S T R U T S T A G R E F E R E N C E

387

Attributes

server: Specifies the base URL. If you omit the server attribute, then Struts pastes the path to the enclosing JSP page. The server attribute gets rendered as the href attribute of <base>.

target: If your app uses frames, then you can specify the name of the frame to which this base URL applies, in the page that defines the frame.

Examples

The simplest, and most useful, example is using the <html:base /> tags by itself:

<head> <html:base />

</head>

The implied base is that of the JSP page itself. This gets rendered as

<head>

<base href="http://www.mycompany.com/mywebapp/"> </head>

Similarly, if you wanted to fix the base of a frame within the current webapp, use this:

<head>

<html:base target="myframe" /> </head>

If you need to set the base to point to another server, then use the server attribute:

<head>

<html:base server="http://www.myothercompany.com" /> </head>

Equivalents

The Struts-Faces taglib (see Chapter 20) contains an <s:base> tag, which accepts a target attribute. There is no equivalent of the server attribute, though.

A hack for the <html:base/> tag is

<base href="<%= request.getScheme() %>://<%= request.getServerName() %>: <%= request.getServerPort() %>/

<%= request.getContextPath() %>/">