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

Beginning Apache Struts - From Novice To Professional (2006)

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

28

C H A P T E R 4 C U S T O M T A G S

//other code omitted.

...

}

When the JSP that contains your tag loads, the servlet container calls all the necessary setXXX() functions so that attributes of your tag are accessible to your tag’s Java code. Using the <bean:write> tag as an example again, at runtime, you could call the getProperty() function or just look at _property to read the value of the property attribute of the

<bean:write> tag.

Helper Classes

In order for your Java handler classes to do anything useful, such as reading the contents of a tag’s body or writing your tag’s output, there are a couple of helper classes you need to know about.

The first is javax.servlet.jsp.tagext.BodyContent, which you use to read your tag’s body, among other things. The function getString() returns your custom tag’s body (assuming it has one) as a String. You can get an instance of BodyContent, if you’ve subclassed BodyTagSupport, by calling the function that has been implemented for you on the base class BodyTagSupport.

BodyContent also gives a Writer instance with which you can write the output of your tag’s transformed body. Calling getEnclosingWriter() on the BodyContent instance will give you a Writer subclass—specifically, a subclass of javax.servlet.jsp.JSPWriter.

To see how all this works, consider a simple <message:write> tag, used like this:

<message:write font-color="red">Hello World!</message:write>

We need the message “Hello World!” to be displayed in the given font color—red, in this instance. A Java handler to accomplish this is shown in Listing 4-4.

Listing 4-4. Implementation of <message:write>’s Handler Class

package net.thinksquared.tags;

import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*;

public class MessageWriteTagHandler extends BodyTagSupport{

protected String _fontColor = "black"; //default font color

public String getFontColor(){ return _fontColor;

}

C H A P T E R 4 C U S T O M T A G S

29

public void setFontColor(String fontColor){ _fontColor = fontColor;

}

public int doAfterBody(){

try{

BodyContent bc = getBodyContent();

JSPWriter out = bc.getEnclosingWriter();

out.write("<font color=\""); out.write(_fontColor); out.write("/">"); out.write(bc.getString()); out.write("</font>");

}catch(Exception ignore){}

//tell the servlet container to continue //processing the rest of the page: return EVAL_PAGE;

}

}!

The TLD File

The last piece of the custom tag puzzle is the TLD (Tag Library Descriptor) file. Each tag you create has to be declared in a TLD file, and this file has to be deployed along with the tag’s Java handler classes. As we’ve seen in the previous section, the servlet container knows where you’ve placed the TLD file because you’ve declared the path in web.xml, the standard servlet configuration file.

Note I’ve included this section mainly for your reference. If you’re itching to write your own custom tag, you may safely skip this section and proceed to Lab 4.

Consider the TLD file declaring the <message:write> tag we developed earlier, as shown in Listing 4-5.

30

C H A P T E R 4 C U S T O M T A G S

Listing 4-5. TLD File Declaring <message:write>

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE taglib

PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<taglib>

<tlibversion>0.0</tlibversion>

<jspversion>1.1</jspversion>

<shortname>message</shortname>

<tag>

<name>write</name>

<tagclass>

net.thinksquared.tags.MessageWriteTagHandler

</tagclass>

<bodycontent>JSP</bodycontent>

<attribute> <name>font-color</name> <required>false</required>

</attribute>

</tag>

</taglib>

As you can see, the TLD file is just an XML file. The root tag is <taglib>, and this contains one or more <tag> tags, which declare your custom tag. Tables 4-1, 4-2, and 4-3 explain each tag on the TLD file. Note that each <taglib> must contain one or more <tag> declarations.

Table 4-1. Tags on the TLD File

Tag

Meaning

taglib

Root tag for the TLD file.

tlibversion

Your version number for this tag library.

jspversion

The JSP version this tag library depends on. Use 1.1.

shortname

The preferred or suggested prefix for tags on this tag library, when you use

 

the tag on your JSP pages. You are of course free to ignore this suggestion.

tag

Contains metadata for a single tag in this tag library.

 

 

C H A P T E R 4 C U S T O M T A G S

31

Table 4-2. The Subtags of <tag>

Tag

Meaning

name

Name of this tag.

tagclass

Name of the Java handler class. Note that this is the fully qualified name of the

 

handler class, e.g., net.thinksquared.tags.MessageWriteTagHandler.

bodycontent

The type of content for this tag’s body. Use JSP.

attribute

Contains metadata for a single attribute on this tag.

 

Table 4-3. The Subtags of <attribute>

 

 

Tag

Meaning

 

 

name

Name of this attribute. This obviously has to be unique on the tag.

required

Indicates if this tag is required (true) or optional (false).

 

 

Lab 4: A Temperature Conversion Tag

In this lab session, you will create, deploy, and test a temperature conversion tag. Here are some specs:

The tag library will contain just one tag called convert, which has one optional attribute.

The optional attribute to indicates the temperature scale to convert to.

By default, to is Fahrenheit.

Conversions are from Celsius to either Fahrenheit or Kelvin.

Note In a production implementation, you’d include some error reporting.

For example, these all convert to 100 Celsius to 212 Fahrenheit:

<temp:convert to="Fahrenheit">100</temp:convert> <temp:convert to="F">100</temp:convert> <temp:convert>100</temp:convert>

while these convert 100 Celsius to 373 Kelvin:

32

C H A P T E R 4 C U S T O M T A G S

<temp:convert to="Kelvin">100</temp:convert> <temp:convert to="K">100</temp:convert>

To create and use this tag, you will have to

1.Prepare the development directory and scripts.

2.Write the Java tag handler.

3.Write the TLD file describing the tag.

4.Write the JSP to test the custom tag.

5.Amend web.xml to register your TLD file.

6.Install the application onto Tomcat.

Step 1: Prepare the Development Environment and Scripts

1.Create a Struts directory in a convenient location on your hard drive.

2.Copy the lab4.zip file on the CD-ROM into this Struts directory.

3.Unzip the contents, making sure you’ve preserved the directory structure.

4.You should see a subdirectory called .\Struts\lab4\.

5.Open .\Struts\lab4\compile.bat in a text editor and amend the PATH environment variable so that it points to your JDK installation.

Note On Windows XP, ME, or 2000, which have built-in unzipping capabilities, the zip file may add an extra lab4 directory in the unzipped path. So, the compile.bat file’s path would be .\Struts\lab4\lab4\ compile.bat. You could move the lab4 folder up or just continue. The compile scripts should work regardless.

Test out your changes by clicking compile.bat. You should get no errors, and you should see a file called lab4.war in .\Struts\lab4\.

In what follows, I’ll refer to all paths relative to .\Struts\lab4\.

C H A P T E R 4 C U S T O M T A G S

33

Step 2: Write the Java Tag Handler

1.Open the file .\src\Converter.java in your favorite text editor.

2.Put in a private String variable called _to. This will correspond to the to attribute of your custom tag.

3.Create getTo() and setTo() methods to get and set the value of _to. The servlet container will use these to get/set the variable _to with the value of the to attribute.

4.Complete the doAfterBody() method, using the specs to guide you. You will need to use helper classes to do this (see Listing 4-4).

5.Note that doAfterBody() must return the integer flag EVAL_PAGE to indicate that the rest of the JSP page is to be evaluated.

6.Compile your work by clicking on compile.bat.

Step 3: Writing the Tag Library Descriptor file

1.Open .\web\WEB-INF\lab4-converter.tld in your favorite text editor.

2.This is an empty tag library descriptor file, containing just the mandatory boilerplate. Create the root <taglib> ... </taglib> tag after the boilerplate.

3.Within the enclosing <taglib> tag, insert the appropriate tags, using Listing 4-5 as a reference.

Step 4: Amend web.xml

web.xml is the standard servlet configuration file. Every webapp must have its own web.xml file, even if it’s a blank one.

Note If you place your TLD files in the WEB-INF directory, you really don’t need to declare them in web.xml. We will, however, for completeness.

1.Open .\web\WEB-INF\web.xml in your favorite text editor. Note that the web directory exists only in development. The compile.bat script later moves the whole WEB-INF directory up, and removes the web folder.

34

C H A P T E R 4 C U S T O M T A G S

2.The web.xml file contains boilerplate text, followed by a <webapp> tag. Insert the tags shown in Listing 4-6 within the enclosing <webapp> tag.

Listing 4-6. Your Addition to web.xml

<taglib> <taglib-uri>/tags/lab4-converter</taglib-uri>

<taglib-location>/WEB-INF/lab4-converter.tld</taglib-location> </taglib>

Note Notice in Listing 4-6 that the path separators are Unix-style slashes (/), not Windows backslashes.

Step 5: Write Your JSP

1.Open the file .\web\test.jsp in your favorite text editor.

2.Put in the taglib declaration for your custom tag library. Remember to use the URI you defined in web.xml.

3.Put in JSP code to test the convert tag. You should at least test all the examples given at the start of this lab.

Step 6: Deploy and Test

1.Shut down Tomcat if it is running.

2.Click compile.bat. This compiles your source code and produces the WAR file, lab4.war.

3.Drop the WAR file into Tomcat’s webapps directory. Remember, if you want to redeploy the lab4 app, you will have to delete its folder under the webapps directory.

4.Use http://localhost:8080/lab4/ to test your work.

If you’re stuck at any point, you might want to consult the answers to this lab. You’ll find them in lab4-answers.zip on the CD-ROM.

C H A P T E R 4 C U S T O M T A G S

35

Professional Java Tools

In this book, I’ve used Windows batch files to compile and prepare WAR files. I’ve done this to keep things as simple as possible. However, in the real world, batch files are not the best way to compile your web applications. A much, much better option is to use Apache Ant (see “Useful Links” for the website).

Ant gives you a platform-independent way of compiling your Java source code. But Ant does much more. You can create different compile configurations easily with Ant. Also, many valuable Java tools integrate with Ant. While using Ant is beyond the scope of this book, I encourage you to download it and try to use it in your projects.

The other area I encourage you to explore is using a real Java integrated development environment (IDE), rather than plain ol’ Notepad. Most IDEs provide tools to simplify creating and editing Java, HTML, and XML, thus making you more productive.

One IDE I highly recommend is the open source Eclipse (see “Useful Links” for the website). A copy of this IDE is on the accompanying CD-ROM.

Useful Links

Apache Ant website: http://ant.apache.org

Eclipse website: www.eclipse.org

Summary

Custom tags are a central piece in Java-based web application frameworks.

Custom tag functionality is implemented by your subclass of either TagSupport or

BodyTagSupport.

Use TagSupport if your custom tag doesn’t have a body and BodyTagSupport if it does.

You need to declare your custom tag in a Tag Library Descriptor (TLD) file.

You might have to register the TLD file’s location in web.xml.

C H A P T E R 5

■ ■ ■

The MVC Design Pattern

Servlet technology is the primary base on which you can create web applications with Java. JavaServer Pages (JSP) technology is based on servlet technology but extends it by allowing HTML content to be created easily.

Note that JSP technology doesn’t replace servlet technology, but rather builds on it, to address some of its deficiencies. Struts follows this pattern, and builds on servlet and JSP technologies to address their shortcomings. These shortcomings are in two broad areas:

Creating a “separation of concerns”: Pieces of code that do different things are bundled separately and given standardized ways of communicating between themselves.

An infrastructure for webapps: This includes things like validating user input, handling and reporting errors, and managing flow control.

If these shortcomings are addressed, the very practical problems of building webapps (robustness, maintainability, localization, etc.) become easier to tackle.

One tool that can be used to make some headway in resolving these issues is an organizing principle called the Model-View-Controller (MVC) design pattern.

WHAT ARE DESIGN PATTERNS?

Design patterns are essentially recipes for solving generic coding problems. They are not algorithms but rather organizational principles for software.

The idea of using “design patterns” to solve common software engineering problems first came to prominence with the book Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley Professional, 1995), by, by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. The authors credit an earlier work, A Pattern Language for Building and Construction (Oxford University Press, 1977) by the architect Christopher Alexander as the inspiration for the idea of design patterns for software.

The MVC design pattern, which is the subject of this chapter, was first used in an AI language called Smalltalk in the 1980s to solve a problem similar to the one we’re discussing here for webapps. A variation on the pure MVC pattern is also used in Swing, Java’s platform-independent GUI toolkit.

37