9Writing CFX Tags with Java
2. Compiling the Java code into the corresponding .class file
3. Registering the new CFX tag in the ColdFusion Administrator
In the next few pages, you’ll learn how to perform each of these steps, producing a very simple CFX
tag along the way. More complicated, fully featured examples will follow later in this chapter.
Writing the Java Code
The actual code for your CFX will be contained within an ordinary Java class file. Like any Java class,
you can write the code in any text editor, such as the Windows Notepad, Macromedia Dreamweaver,
or the editor of your choice. Once the code is written, you can use the
javac utility from the Java
SDK to compile the class (discussed below, in the “Compiling the CFX Tag” section).
NOTE
Of course, you are also free to use a free or commercial Java Integrated Development Environment (IDE), which will be able to offer
such niceties as automatic code completion, automatic compilation, and integrated help. One such IDE is Sun’s ONE Studio (for-
merly called Forte for Java); another is Borland’s JBuilder product.
This chapter’s first example will be a simple CFX tag called <CFX_HelloWorld>. Listing 30.1 shows
the Java source code for the tag.
Listing 30.1 HelloWorld.java—Creating the <CFX_HelloWorld> Tag with Java
import com.allaire.cfx.* ;
public class HelloWorld implements CustomTag {
public void processRequest( Request request, Response response )
throws Exception
{
// Make sure a NAME attribute is passed to the tag
if ( !request.attributeExists(“NAME”) ) {
throw new Exception(“The NAME attribute is required!”);
};
// Make sure an AGE attribute is passed as well
if ( !request.attributeExists(“AGE”) ) {
throw new Exception(“The AGE attribute is required!”);
};
// Respond by inserting a text message in the calling ColdFusion file
// The text will appear in place of the CFX tag in the final Web page
response.write(“<P>Hello there “ + request.getAttribute(“NAME”) + “!”);
response.write(“<BR>I hear you turned “ + request.getAttribute(“AGE”));
response.write(“ sometime during the past year. Happy birthday!<BR>”);
}
}
Even if you’ve never seen a line of Java code before, you can probably guess what this tag will do
when it is used in a ColdFusion page. That’s right, it will display a “Hello, World” type of message
which contains the values of the
NAME and AGE attributes that get passed to the tag.
Komentarze do niniejszej Instrukcji