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

Beginning Apache Struts - From Novice To Professional (2006)

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

88

C H A P T E R 8 B A S I C S T R U T S T A G S

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Figure 8-3. Displaying errors

To display a generic error message, not connected to any real form property, you can use a special global property. In your ActionForm or Action, you’d use the key ActionMessages. GLOBAL_MESSAGE:

errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(...));

and the property value org.apache.struts.action.GLOBAL_MESSAGE on the <html:errors> tag:

<html:errors property="org.apache.struts.action.GLOBAL_MESSAGE"/>

Synopsis of HTML and Bean Tag Libraries

The previous section describes all the tags you’ll use 70 percent of the time in your Struts webapps. The remaining 30 percent we’ll describe in Chapters 10, 11, and 14. Appendix C is a comprehensive reference for all tags.

At this point, a synopsis of the HTML and Bean tags would be useful to you. Table 8-1 lists tags on the HTML library and their purpose. Table 8-2 does the same for the Bean tag library. You can find the details on each tag in Appendix C. Tables 8-1 and 8-2 are based on documentation made available by the Apache Software Foundation. The Apache License is available at http://www.apache.org/licenses/LICENSE-2.0.

C H A P T E R 8 B A S I C S T R U T S T A G S

89

Table 8-1. Synopsis of the HTML Tag Library

Tag

Usage/Comments

base

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

 

which all relative paths in your JSP will be calculated.

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.

form

Defines a form. The action and focus attributes are the most

 

useful, followed by the enctype property described in Chapter 11.

checkbox

Generates a check box input field.

file

Generates a file select input field.

hidden

Generates a hidden field.

multibox

Generates a number of check box input fields. Used in conjunction

 

with indexed properties.

option

Generates a select option.

options, optionsCollection

Generates a list of select options.

password

Generates a password input field.

radio

Generates a radio button input field.

select

Generates a select element.

text

Generates a textual input field.

textarea

Generates an HTML textarea element.

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.

errors

Displays error messages.

messages

An iterator for error messages and ordinary messages.

img

Generates an HTML img tag.

link

Generates a hyperlink.

rewrite

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

 

JavaScript functions.

 

 

90 C H A P T E R 8 B A S I C S T R U T S T A G S

Table 8-2. Synopsis of the Bean Tag Library

Tag

Usage/Comments

message

Writes static text based on the given key.

write

Writes the value of the specified JavaBean property.

cookie/header/parameter

Each defines a scripting variable based on the specified

 

cookie/header/parameter.

define

Defines a scripting variable based on the specified JavaBean.

page

Exposes a page-scoped variable as a JavaBean.

include

Allows you to call an external JSP or global forward or URL and

 

make the resulting response data available as a variable. The

 

response of the called page is not written to the response stream.

resource

Allows you to read any file from the current webapp and expose

 

it either as a String variable or an InputStream.

size

Defines a new JavaBean containing the number of elements in

 

a specified Collection or Map.

struts

Exposes the specified Struts internal configuration object as

 

a JavaBean.

 

 

Lab 8: Contact Entry Page for LILLDEP

In this lab, you will complete the implementation for the main page for LILLDEP. This page is called full.jsp.

1.Open \lilldep\web\full.jsp in the editor. Put in the missing taglib declarations. Which libraries would you use? (The TLD files are in \web\WEB-INF\.)

2.Modify web.xml to include the tag library locations.

3.Implement the tags for the missing properties. The properties for this form are listed in Lab 6. Use the keys found in \web\resources\Application.properties to display any messages you might need.

4.Put in error tags corresponding to each validated field in Lab 6. Also put in an error tag for the error encountered when saving a contact in Lab 7.

5.Implement the submit button. What is the name of the handler for this form?

Note The source code answers are in the answers folder in the LILLDEP distribution. The answers to

questions raised in this lab are found in Appendix D.

C H A P T E R 8 B A S I C S T R U T S T A G S

91

Useful Links

FreeMarker, a powerful open source template engine: http://freemarker. sourceforge.net

Velocity, a simpler, lightweight open source template engine from Apache: http://jakarta.apache.org/velocity/

Pro Jakarta Velocity: From Professional to Expert, by Rob Harrop (Apress, 2004): www.apress.com/book/bookDisplay.html?bID=347

Summary

In this chapter, you have seen how the basic Struts tags work to display form data and error messages.

The Struts tags to display form data and error messages are in the HTML and Bean libraries.

Forms have an associated form handler, which is a particular combination of

ActionForm and Action subclasses.

Form data is first passed through simple validation (ActionForm) before business logic is processed (Action).

Struts handles the redisplay of badly filled forms and error messages for the necessary fields.

C H A P T E R 9

■ ■ ■

Configuring Struts

Up until now, I’ve presented portions of Struts along the lines of the MVC design pattern. In Labs 6, 7, and 8, you’ve implemented these portions yourself for the LILLDEP webapp. What’s missing is the way Struts ties together the various Model-View-Controller portions.

Struts uses a single configuration file called struts-config.xml to store this information. The Struts distribution comes bundled with samples of this file, which you can copy and amend for your own use.

The Structure of struts-config.xml

Unsurprisingly, struts-config.xml holds data in XML format. There are several sections, each of which handles configuration for specific portions of Struts:

Form bean declarations: This is where you map your ActionForm subclass to a name. You use this name as an alias for your ActionForm throughout the rest of the struts-config.xml file, and even on your JSP pages.

Global exceptions: This section defines handlers for exceptions thrown during processing.

Global forwards: This section maps a page on your webapp to a name. You can use this name to refer to the actual page. This avoids hardcoding URLs on your web pages.

Form handlers: Remember the form handlers I mentioned in the previous chapter? This is where you declare them. Form handlers are also known as “action mappings.”

Controller declarations: This section configures Struts internals. Rarely used in practical situations.

Message resources: This section tells Struts where to find your properties files, which contain prompts and error messages.

93

94

C H A P T E R 9 C O N F I G U R I N G S T R U T S

Plug-in declarations: This is where you declare extensions to Struts. You will use two important plug-ins: Tiles and Validator.

These sections must be placed in this order. Not all sections need be present. For example, you might not want to take advantage of the global exception handling facility. In this case, your struts-config.xml file would not contain the global exceptions section.

Note Earlier versions of Struts had a “data sources” section before the form bean declarations. This data sources section allowed you to preconfigure JDBC data sources for your webapp. This section has since been deprecated.

Among the seven sections, the form bean, form handler (or action mapping), and message resources sections are the most important, and you must master them before you can use Struts.

Before I introduce the various sections, let’s take a look a simple struts-config.xml file, the one for the Registration webapp.

Configuring the Registration Webapp

The struts-config.xml file (shown in Listing 9-1) for the Registration webapp requires just the form bean, global exceptions, global forwards, form handler (or action mapping), and message resources sections.

Listing 9-1. struts-config.xml for the Registration Webapp

<?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE struts-config PUBLIC

"-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>

<form-beans> <form-bean

name="RegistrationForm"

type="net.thinksquared.registration.struts.RegistrationForm"/> </form-beans>

C H A P T E R 9 C O N F I G U R I N G S T R U T S

95

<global-exceptions>

<exception key="reg.error.io-unknown" type="java.io.IOException"

handler="net.thinksquared.registration.ErrorHandler"/>

<exception key="reg.error.unknown" type="java.lang.Exception" path="/errors.jsp" />

</global-exceptions>

<global-forwards>

<forward name="ioError" path="/errors.jsp"/> </global-forwards>

<action-mappings> <action

path="/Registration"

type="net.thinksquared.registration.struts.RegistrationAction"

name="RegistrationForm"

scope="request"

validate="true"

input="/Registration.jsp">

<forward name="success" path="/Success.jsp"/>

</action> </action-mappings>

<message-resources parameter="Application"/>

</struts-config>

The three main sections should be immediately obvious in Listing 9-1: the form beans section is enclosed by the <form-beans> tag, the form handlers section by the <action-mappings> tag, and the single message resource section by the <message-resources> tag. I’ll describe these sections in detail next.

Declaring Form Beans

The form bean section is where you give your ActionForm subclasses names, which can be used both in struts-config.xml and on your JSP pages.

96

C H A P T E R 9 C O N F I G U R I N G S T R U T S

The declaration consists of a single enclosing <form-beans> tag (note the plural), and one or more <form-bean> (note the singular) tags, as shown in Listing 9-2.

Listing 9-2. The Form Beans Section

<form-beans> <form-bean

name="RegistrationForm"

type="net.thinksquared.registration.struts.RegistrationForm"/> </form-beans>

A <form-bean> tag has two attributes:

name: The name attribute is a unique label for an ActionForm subclass. In Listing 9-2, the name is RegistrationForm, but it could be anything you like, as long as it is unique among other form bean declarations and qualifies as an XML attribute value.

type: The type attribute is the fully qualified class name for that ActionForm subclass.

With this declaration, you can use the name RegistrationForm to refer to the ActionForm subclass, net.thinksquared.registration.struts.RegistrationForm.

Declaring Global Exceptions

Global exceptions allow you to catch uncaught runtime exceptions that occur in your Action subclasses, displaying them with a custom error message. This certainly lends a little more polish to your application, compared to the default Tomcat error page. Listing 9-3 shows two ways you can define an exception handler.

Listing 9-3. Declaring Global Exception Handlers

<global-exceptions>

<exception key="reg.error.io-unknown" type="java.io.IOException"

handler="net.thinksquared.registration.IOErrorHandler"/>

<exception key="reg.error.unknown" type="java.lang.Exception" path="/errors.jsp"/>

</global-exceptions>

C H A P T E R 9 C O N F I G U R I N G S T R U T S

97

The <global-exceptions> tag contains global exception handlers, each represented by an <exception> tag. Each <exception> tag has two required attributes:

key: An error key. When an exception handler is fired, an ActionMessage with this key is created and put on the request. This error message gets pasted on the JSP containing an <html:errors> tag that is finally displayed. Note that key is a required attribute, which you have to specify even if you don’t use it.

type: Describes the type of error that is caught. Struts will first try to find the error class that matches the declared types. If none matches exactly, then Struts goes up that error’s superclass tree, until it finds a match with a declared exception.

There are two ways you can handle the caught exceptions: using a path attribute to point to a JSP page that displays the error message, or using a handler attribute, which is a fully qualified class name of your ExceptionHandler subclass—that is, your handler subclasses:

org.apache.struts.action.ExceptionHandler

You only have to override the execute() function:

public ActionForward execute(Exception ex,

ExceptionConfig ae,

ActionMapping mapping, ActionForm form, HTTPRequestServlet request, HTTPResponseServlet response)

As you can see, this is nearly identical to Action.execute(), apart from the extra first two arguments. You should declare the “next” page ins a <global-forwards> section (see the next section), so that mapping can resolve it.

In most instances, using a custom ExceptionHandler subclass is overkill unless you have a special requirement to do so.

Declaring Global Forwards

You use global forwards to define forwarding paths accessible to all Actions or ExceptionHandlers. In fact, all such paths will be accessible as long as you have an ActionMapping instance initialized by Struts. This is certainly the case for the execute() functions in Action or ExceptionHandler.

Global forwards are defined within an enclosing <global-forwards> tag, within which you may place as many <forward> tags as you wish, as shown in Listing 9-4.