Chapter 18. JavaServer Pages and Tag Libraries

Understanding JavaServer Pages (JSPs)

The JSP technology is a part of the J2EE standard that addresses the generation and presentation of dynamically generated XML-based content, which is most often HTML or WML content. It is generally focused more on the presentation of HTML than servlets are. The key advantages of JSPs are

  • They offer a clean separation of presentation and business logic, and they encourage the use of the Model-View-Control (MVC) design pattern through the ability to separate the presentation layer of an application from the business layer.

  • They do not require extensive Java programming, simplifying the generation of dynamic content by engineers who are more focused on the HTML presentation than a J2EE developer is. Many JSPs require no Java programming; the author just embeds XML tags into the HTML source code.

JSPs allow the mixing of HTML directives with Java code to generate static and dynamic content easily.

A J2EE server such as WebLogic translates a JSP into a servlet, which then runs in the servlet container. The steps that WebLogic Server performs for a JSP request are

  1. A request for a JSP comes into the server. Commonly the URL portion of the request ends with a .jsp extension. However, the URL could instead be mapped to a JSP in the configuration of the web application.

  2. The server compares the time stamp on an internal cache to see whether the requested JSP file on the file system is newer than the cached version.

    Tip

    WebLogic Server can be configured to not check the JSP file timestamp or to only check it after a certain time period. This is commonly used on production systems where the JSP file will not be changing during runtime. The performance of the server is improved as it does not have to query the file system every time a JSP is requested. This setting is associated with each Web application within the server.

    To change this setting, log into the WebLogic Server console (traditionally at http://<hostname>:7001/console) and select the Web application you want to change. Select Edit Web Application Deployment Descriptors... at the top of the right pane. If the left pane does not show a control for WebApp Ext, then select the link Configure a New Web App Ext Descriptor... in the right pane. Then go back and select JSP Descriptor under the WebApp Ext control. For the value Page Check Seconds, set the value to “0” (zero) if you want WebLogic Server to check the timestamp on the JSP on every request regardless of how long it has been since the server last checked. If you set this to a positive value greater than zero, then WebLogic Server will check the file system at the interval defined. If you set it to –1 then the WebLogic server will never check the file system.

  3. If there is no cached version of the JSP or if the JSP file is newer than the cached version, the server converts the JSP file into a Java file. This Java file is a type of servlet that contains all the HTML markup and Java code from the JSP file.

  4. The Java file is compiled into a servlet and run in the servlet container just like a normal servlet.

  5. If the JSP file is not newer than the internally cached version, the server runs the servlet. Because the servlet is already compiled and installed, this process is very quick.

That JSPs can be dynamically compiled gives them much of their power. Additionally, because they are based on servlets they have all the power of servlets, including multithreaded concurrent access and database access through JDBC.

Where JSPs and servlets are different is that a JSP is an HTML file first and a Java file second, with only small, if any, amounts of Java code. Servlets, on the other hand, are Java classes first with HTML embedded in them. It is important to understand that any HTML page is already a JSP. You can just rename it with a .jsp extension, and the Web server will automatically convert it to a servlet.

JSPs make application development easier because they are automatically compiled by the Web server. Servlets require a standard development process—edit, compile, and install. With a JSP, you just edit and the Web server takes care of the rest.

JSP Elements

A JSP is an HTML page with special tags embedded in it to allow the page to access the Web stream or enable it to access other Java objects.

There are different types of JSP tags depending on their use:

  • Expressions are of the form <%= expression %>. They are evaluated by the JSP compiler, and they output a java.lang.String. If the result of the expression is not already a string, the JSP compiler automatically converts it.

  • Declarations look like <%! code %>. They are normally used with expressions or scriptlets. A declaration creates a member variable in the servlet that is defined for the JSP.

  • Scriptlets are of the form <% code %>. They are used for regular Java code that is inserted into the JSP output stream.

Predefined Variables

The JSP specification defines a set of predefined variables that can be used in a JSP. These variables help you access the request, the session, and other variables in the JSP runtime. The variables are part of the servlet that is created from the JSP:

  • request—. This is the javax.servlet.http.HttpServletRequest that is associated with the page request. It provides all the methods available when you’re using this class with servlets.

  • response—. This is the HttpServletResponse associated with the Web stream. It can be used to set HTTP status codes (for example, 404 - file not found) and to specify the content type of the response. Of course, this variable has access to all the methods on the HttpServletResponse as well.

  • out—. A javax.servlet.jsp.JspWriter is used to put data into the output stream. It works similarly to servlets when the output to the ServletOutputStream is retrieved from the HttpServletResponse. This variable is usually used only in scriptlets because normal HTML or text can be output without directly using any of the JSP facilities.

  • session—. The javax.servlet.http.HttpSession object is associated with this session. As mentioned in Chapter 17, “Introduction to Servlets,” an HttpSession is used to identify a user between invocations of a servlet. It can be used in the same way for a JSP. This is an easy way to have a stateful session with the client browser.

  • application—. The javax.servlet.ServletContext of the JSP. This is the same variable that can be obtained in a servlet by calling getServletConfig().getContext(). A ServletContext defines a set of methods that the servlet or JSP uses to communicate with the servlet container they are located in. For example, servlets have a common log file that can be accessed via this object. To use the log file, you would, in a JSP, write

    application.log( "Something didn't work" );
    

This statement writes the specified message to the servlet log file.

  • config—. The javax.servlet.ServletConfig for the JSP. It can be used to retrieve initialization parameters for the JSP in much the same way that initialization parameters are retrieved for a servlet.

  • pageContext—. A javax.servlet.jsp.PageContext. To an extent, a pageContext is a wrapper for all the other attributes. It provides access to most of the page attributes and provides a place to store shared data.

Expressions

Expressions are used to insert strings and other variables into the output of the JSP stream. A variable is converted to a string by the JSP engine if needed. Expressions allow dynamic information to be embedded into an HTML page by being interpreted with the HTML stream. For example, you can modify the Chapter 17 example so that it’s a JSP. To do so, you write HTML code with embedded expressions that generate the same output as the servlet did, as shown in Listing 18.1.

Example 18.1. HTML Code with Embedded Expressions

<html>
<head>
    <title>Hello!</title>
</head>

<body>

<!--- get the remote host, very similar to the servlet example -->
Welcome <%= request.getRemoteHost() %> <br>

<!--- get the User-Agent - also similar to the servlet example -->
Your browser id string is <%= request.getHeader( "User-Agent" ) %>

</body>
</html>

In this case, the JSP engine does not need to coerce the result of the call to getRemoteHost() because it already is a string. However, you can now add code to display the content length by calling getContentLength() on the request. This code returns an integer that is simply the length in bytes of the content after the HTTP header (see Listing 18.2).

Example 18.2. Displaying Information from the HttpServletRequest

<html>
<head>
    <title>Hello!</title>
</head>

<body>

<!--- get the remote host, very similar to the servlet example -->
Welcome <%= request.getRemoteHost() %> <br>

<!--- display the Content-Length HTTP header element -->
The Content-Length field is <%= request.getContentLength() %><br>

<!--- get the User-Agent - also similar to the servlet example -->
Your user agent string is <%= request.getHeader( "User-Agent" ) %>

</body>
</html>

By automatically converting the result of getContentLength() to a string from an integer, the JSP engine further simplifies the task of writing a JSP page. The code does not require you to write something like this:

The Content-Length field is

<%= Integer.toString( request.getContentLength() ) %><br>

Again, the goal is to minimize the amount of Java code that a JSP developer needs to write. Ultimately, all the output from the JSP page is a string that will be rendered by the browser like in Figure 18.1.

Output from the sample JSP.

Figure 18.1. Output from the sample JSP.

Expressions can also be included in a JSP with XML syntax. The syntax in Listing 18.1 would then be changed to that shown in Listing 18.3.

Example 18.3. Using JSP XML Expressions

<html>
<head>
    <title>Hello!</title>
</head>

<body>
<!--- get the remote host, very similar to the servlet example -->
Welcome
<jsp:expression>
request.getRemoteHost()
</jsp:expression>
<br>

<!--- get the User-Agent - also similar to the servlet example -->
Your user agent string is
<jsp:expression>
request.getHeader( "User-Agent" )
</jsp:expression>

</body>
</html>

XML syntax improves the machine readability of the document and provides the flexibility of performing an XML transformation to programmatically change the page from one style to another, but can make it more difficult for human readability. However, the JSP engine treats both forms exactly the same, so it is up to you to determine the best form.

Declarations

A JSP declaration defines a variable to be used in a later scriptlet or expression. It has the form <%! declaration %> (see Listing 18.4).

Example 18.4. Using JSP Declarations

<html>
<head>
<title>Hello!</title>
<body>
<%! private String lastVisitor = null; %>
<b>Hello <%= request.getRemoteHost() %></b><br>
The last visitor to our site came from <%= lastVisitor %>

<% lastVisitor = request.getRemoteHost(); %>
</body>
</html>

In Listing 18.4, the string, lastVisitor, is defined by the declaration and then used later in the expression. The last line sets the lastVisitor variable to the current visitor’s remote host.

It is important to understand that the JSP compiler translates declarations into member variables in the servlet. This means that multiple invocations of the same JSP use the same variable. Recall from Chapter 17 that the default behavior for servlets is for all requests to be serviced by the same servlet but through multiple threads. The same is true of JSP pages because they are servlets.

However, this means that the same caveats that apply to servlets and threads also apply to JavaServer Pages. Listing 18.4 does not use synchronization techniques to serialize access to the variable lastVisitor. If multiple simultaneous requests come in to this JSP from different remote machines, the variable could be overwritten with incorrect information.

One way to add thread safety to Listing 18.4 is to use standard Java synchronization techniques. Listing 18.5 shows using these techniques.

Example 18.5. JSP Declaration Example Using Synchronization

<html>
<head>
<title>Hello!</title>
<body>
<%! private String lastVisitor = null; %>
<b>Hello <%= request.getRemoteHost() %></b><br>

The last visitor to our site came from <% synchronized( this ) { %>
<%= lastVisitor %>
<% lastVisitor = request.getRemoteHost(); } %>
</body>
</html>

As with JSP expressions, there is an XML syntax for declarations too:

<jsp:declaration>
//
// an alternate way to declare the same variable as in
// Listing 18.4
//
    private String lastVisitor;
</jsp:declaration>

After you restart the server and run the JSP, the lastVisitor variable is null; hence, you will see the output shown in Figure 18.2.

Output from the first run after a server restart.

Figure 18.2. Output from the first run after a server restart.

After the JSP has been run once, the lastVisitor variable is set correctly, as shown in Figure 18.3.

Output from the second run after a server restart.

Figure 18.3. Output from the second run after a server restart.

Scriptlets

The last line of the syntax shown in Listing 18.4

<% lastVisitor = request.getRemoteHost() %>

is slightly different because it represents a JSP scriptlet. A scriptlet allows the developer to embed any Java code within the JSP page. In this example, you reset the contents of the lastVisitor variable to be the current visitor so that on the next visit to the page the variable will display the correct output.

Scriptlets can be used anywhere within the JSP. They must be used for code that is not meant to be converted into a string and inserted into the output HTML stream. In Listing 18.4, when you reassigned the lastVisitor variable, no output needed to be generated; only code needed to be executed in this case.

Other Scripting Elements

When creating a JSP with scriptlets, you may need to import classes to use within the JSP. You do so with the page directive:

<%@ page import="java.util.*, java.math.*" %>

This directive generates an import statement in the resulting servlet. Page directives traditionally live at the top of the JSP.

Several other page attributes are commonly used:

  • buffer—. Specifies the buffering model for the predefined out variable. It can be either "none" to turn off all buffering of the JSPWriter or a size in kilobytes. For example, having buffer="16kb" after the page directive specifies a buffer size of 16 kilobytes. The suffix kb is required by the JSP 1.2 spec. The buffer attribute is used to control the size of the output buffer of the out variable. It defaults to 8 kilobytes. This means that every 8KB of output generated will be sent to the browser. It is more efficient to send data in larger packets, however, if your JSP page generates only small amounts of data; setting the size too high will result in wasted memory. Setting it to the string "none" results in no buffering.

    Tip

    You can use buffer for debugging when you want to see partial results from the JSP by setting the buffer to none. The results from the JSP will be sent to the browser as they are generated. This setting should not be used in a production environment as it will put a greater strain on network and CPU resources.

  • isThreadSafe—. Tells the JSP compiler whether the generated servlet should implement SingleThreadModel. The default is "false". Set this attribute to "true" if your JSP needs to be single threaded. As mentioned in Chapter 17, servlets are, by default, shared within WebLogic Server. Because JSP pages are converted to servlets, they are shared also. If your JSP page accesses a resource that requires serial access, setting this attribute to "false" tells the servlet container that only one thread at a time should access this JSP page. However, the same caveats exist for JSP pages as for servlets, namely that the servlet container is allowed to create multiple instances of the servlet to service requests. Each instance will have only one thread using it at a time, but multiple instances may exist at the same time. Listing 18.5 could use this technique as an alternative to synchronize access to the JSP.

  • info—. Contains an arbitrary string that can be retrieved by calling getServletInfo() within the JSP page. This variable can be used to provide information about the JSP page to the WebLogic console. Commonly, version information is stored in this variable.

  • contentType—. Specifies the MIME type of the resulting page. This value can also be set by calling response.setContentType() from within the JSP. It can be used to set the content type to something besides "text/html". For example, if your JSP page returns only textual information, you can set the contentType to "text/plain".

  • pageEncoding—. Defines the character encoding for the JSP. The default value is "ISO-8859-1", but you should set it to the character encoding that you will use in your pages. This value can also be set by calling response.setLocale() in your JSP. This attribute is commonly used to specify an alternate character encoding for the page. If you return characters in the UTF8 character set, you can include pageEncoding="utf8" in your JSP page.

Another directive is include, which allows you to include another file within your JSP. There are two types of include directives. The first uses syntax similar to the page directive. It looks like this:

<%@ include file="header.html" %>

This directive tells the JSP compiler to include the entire contents of the header.html line in the JSP. The JSP compiler does not compile the JSP until it has included all files specified with the include directives. After the compiler includes all the files, it translates the JSP.

The other include directive uses a different type of syntax, similar to the XML syntax you have seen already. It has this form:

<jsp:include page="header.txt" />

This directive includes the header.txt file, but only at runtime. The JSP compiler does not parse or otherwise interact with this file. The entire contents of the file are included in the output stream for the JSP without being interpreted at all on the Web server.

The last directive is taglib. We will cover tag libraries later in this chapter.

Using JavaBeans

JavaBeans are a standardized format for Java classes. Basically, they define a pattern that is used when creating a class; this pattern allows for fast and easy inspection of the elements and methods of the class. It is important to understand that JavaBeans are not directly related to Enterprise JavaBeans (EJBs), other than that they are both Java component models. JavaBeans are Java classes that follow a simple design pattern:

  • They have at least a no argument constructor.

  • They have get and set methods for all their member variables that are named the same as the variables except that the first letter is capitalized. For example, if a JavaBean has a member variable named firstName, it also must have a getFirstName() method and a setFirstName() method.

Instantiating JavaBeans in JSP

JavaBeans can be used easily in a JSP to help improve reusability of the beans without embedding large amounts of Java code into the JSP. The first step in using a bean in a JSP is to create it using the JSP directive:

<jsp:useBean id="sample" class="com.xigole.examples.Examples" />

This directive tells the JSP compiler to instantiate an object of type "com.xigole.examples.Example" and assign it to the variable named "sample".

Manipulating JavaBean Properties in a JSP

After you create a JavaBean, you can get and set the properties of the bean in two different ways. The first is to use XML syntax:

<jsp:setProperty name="sample"
          property="sampleProperty"
          value="This is the sample property" />

Likewise, to get properties from a bean, you use the following:

<b>The value of the sampleProperty is
<jsp:getProperty name="sample" property="sampleProperty" /></b>

The other method of manipulating bean properties is to access the bean through standard JSP tags, using the name of the bean. For example:

<b>The value of the sampleProperty is <%= sample.getSampleProperty() %></b>

Setting Bean Properties from the Request

A common usage of beans is to package the variables of the HttpServletRequest for easy manipulation. One way to do this is to include a call to request.getParameter() in the <jsp:setproperty> call. Normally, you would use code like this:

<jsp:setProperty name="sample"
          property="sampleProperty"
          value='<%= request.getParmeter("sampleProperty") %>' />

Notice in this example the use of both single quotation marks and double quotation marks. Using them both is required so that the JSP compiler can tell which quotation marks belong to which part of the statement. Attribute values can be enclosed in single or double quotation marks, and we take advantage of that usage here to not confuse the JSP compiler.

JSP allows you to automatically set bean properties from the request as well. The syntax for setting them is

<jsp:setProperty name="sample" property="*" />

This statement sets the property for all properties in the bean that have parameters with the same name. That is, there must be a parameter in the HttpServletRequest with the same name as the bean property. Any missing bean properties are silently ignored. Any additional parameters in the HttpServletRequest that are not used by the bean are silently ignored too. Again, you need to understand that the bean property names and the request parameter names must match exactly, including case, for this approach to work.

Creating the JavaBean Class

As mentioned before, the JavaBean class abides by certain design patterns to allow the JSP compiler to easily access the properties of the bean. The primary requirements are for the bean to have a no argument constructor and for the get and set methods to mirror the member variables. A sample bean might look like the one shown in Listing 18.6.

Example 18.6. SampleJavaBean.java

package jspexample;

public class SampleJavaBean
{
    private String    sampleProperty;

    public SampleJavaBean()
    {
    }

    public void setSampleProperty( String property )
    {
        sampleProperty = property;
    }

    public String getSampleProperty()
    {
        return( sampleProperty );
    }
}

The bean has a single member variable named sampleProperty. There also are set and get methods for this member variable; in each case, the variable name has the first letter in uppercase and the rest of the variable name the same.

It is important to note that a JavaBean does not have to be just a simple container for known variable names. It is perfectly legal, and even encouraged, for a bean to have methods that are more complex. The sample bean can have a method to persist its data to a database. This method can be called from the JSP using scriptlets.

JavaBean Example

Now you can create a simple HTML form and a JavaBean to hold the data from the form. The JSP, named beanExample.jsp, looks like Listing 18.7.

Example 18.7. beanExample.jsp

<html>
<head>
<title>JavaBean form example</title>
</head>
<body>
<form action="/myFirstWebApp/beanExample.jsp" method="get">
    <b>JavaBean form example</b><br>
    <b>User name:</b> <input type="text" name="userName"><br>
    <b>Password:</b> <input type="password" name="password"><br>
    <b>Email Address:</b> <input type="text" name="email"><br>
    <input type="submit" value="Submit">
</form>

<jsp:useBean id="example" class="jspexample.JavaBeanExample" />

<jsp:setProperty name="example" property="*" />

<%
    if( example.getUserName() != null )    // then we already did the set
    {
%>
        <p><b>The user name entered is: </b><jsp:getProperty name="example" property="userName" /></p>
        <p><b>The password entered is: </b><jsp:getProperty name="example" property="password" /></p>
        <p><b>The email address entered is: </b><jsp:getProperty name="example" property="email" /></p>
<%
    }
%>
</body>
</html>

The JavaBean, named JavaBeanExample.java in the src/jspexample directory, looks like Listing 18.8.

Example 18.8. JavaBeanExample.java

package  jspexample;

public class JavaBeanExample
{
    private String    userName;
    private String password;
    private     String    email;

    public JavaBeanExample()
    {
    }

    public void setUserName( String name )
    {
        userName = name;
    }

    public String getUserName()
    {
        return( userName );
    }

    public void setPassword( String pass )
    {
        password = pass;
    }

    public String getPassword()
    {
        return( password );
    }

    public void setEmail( String userEmail )
    {
        email = userEmail;
    }

    public String getEmail()
    {
        return( email );
    }
}

The first run with this JavaBean looks like Figure 18.4.

Output from the first run of the JavaBean example.

Figure 18.4. Output from the first run of the JavaBean example.

Then, after you enter values into the HTML form, the result looks like Figure 18.5.

Output from the second run of the JavaBean example.

Figure 18.5. Output from the second run of the JavaBean example.

Tag Libraries

Tag libraries extend the JSP language to encapsulate business rules and other functionality without embedding Java code. They encourage the division of presentation logic from business logic by allowing the tags to be used in any JSP. Hundreds of available tag libraries perform a wide variety of tasks, and you can easily create your own. Additionally, as of this writing, JSR52, the JavaServer Pages Standard Tag Library (JSTL), is nearing completion. This library will give the Java community a set of standardized tags that will eventually become part of the J2EE standard. JSTL encapsulates some core functionality that is commonly used by JSP applications. Additionally, WebLogic Server includes tag libraries to help validate HTML forms, manage data caches, and perform general-purpose flow control and looping operations. WebLogic Portal Server supplies additional tags to help JSP developers to manage portal content and behavior.

Parts of a Tag Library

A JSP custom tag library has two components. The first is the tag handler class, which defines what the application server does when it encounters the tag. This Java class extends either javax.servlet.jsp.tagext.TagSupport or javax.servlet.jsp.tagext.BodyTagSupport. A class that extends one of these two does the work of the custom tag library.

The other part of a custom tag library is the library descriptor file. This file associates an XML tag within the JSP with the Java class that does the work of the tag. The tag library descriptor (TLD) file is an XML file that contains this mapping and other information about the tag library.

Implementing a Custom Tag Library

Now it’s time to create a simple custom tag that prints the current date and time with an optional message that you supply in the call from the JSP. Certainly, there are simpler ways to print this information, but this approach will work for this small example.

Start by implementing the Java class. You first must decide from which of the two classes you are going to extend. The TagSupport class is used for tags that do not process the body of the custom tag. In this context, the body is the HTML or other code that is between the opening and closing tags. In the JSP, the TagSupport-based tag takes this form:

<om:SampleTag attribute1="hello" />

The BodyTagSuppport class is extended if your custom tag needs to process the information in the body of the tag. In the JSP, it takes this form:

<om:SampleTag attribute1="hello">
    body
</om:SampleTag>

The simple example shown in Listing 18.9 does not need to process the body of the tag and so will extend from TagSupport. This file, named DateTag.java, is in myFirstServlet/WEB-INF/src/jspexample.

Example 18.9. DateTag.java

package jspexample;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import java.util.*;

//
// Simple custom tag library to output the current date and time that the server
// is running in.
//

public class DateTag extends TagSupport
{
    private String    outputMessage = null;

    public int doStartTag()
    {
        try
        {
            JspWriter out = pageContext.getOut();
            Date now = new Date();
            if( outputMessage == null )
                out.print( "The current date and time is " );
            else
                out.print( outputMessage + " " ) ;
            out.print( now.toString() );
        }
        catch( IOException ioe )
        {
        System.err.println( "caught exception in DateTag: " + ioe );
    }
        return( SKIP_BODY );
    }

    public void setMessage( String message )
    {
        outputMessage = message;
    }
}

You need to define the tag library descriptor file for this tag so that it can be used in JSP pages. Listing 18.10, named dateTag.tld, lives in myFirstWebApp/WEB-INF.

Example 18.10. datetag.tld

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
      "weblogic-jsptaglib_1_1.dtd">

<taglib>
    <tlib-version>1.0</tlib-version>
    <jsp-version>1.2</jsp-version>
    <short-name>om</short-name>
    <uri>http://www.objectmind.com/schema/jsp/dateTag/1.1/</uri>
    <displayname>Simple Date</displayname>
    <description>A simple date tag library</description>
    <tag>
        <name>simpledate</name>
        <tag-class>jspexample.DateTag</tag-class>
        <body-content>EMPTY</body-content>
        <attribute>
            <name>message</name>
            <required>false</required>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
    </tag>
</taglib>

Using the Custom Tag in a JSP

To use the custom tag in a JSP, you simply need to include it and use it. Listing 18.11 shows a small JSP file that does just that.

Example 18.11. DateTagSample.jsp

<html>
<head>

<%@ taglib uri="/WEB-INF/dateTag.tld" prefix="om" %>

<title>A simple custom JSP tag library example</title>
</head>

<body>
<b><om:simpledate /></b><br>
<b><om:simpledate message="Now the current date and time is" /></b>
</body>
</html>

Running DateTagSample.jsp produces the output shown in Figure 18.6.

Output from the tag library example.

Figure 18.6. Output from the tag library example.

Putting It All Together: Using the Tag Library in WebLogic

Now you have the Java class that will be used to implement the custom tag and the tag library descriptor (TLD) that will be used to describe the tag library to WebLogic. Deployment of the tag library is fairly straightforward as we will use the examples domain that is shipped with WebLogic 7.0. There are two methods for deploying a custom tag library.

The first method is to create files needed for the tag library in a directory underneath the Web application that will be using it. Say you have a Web application named firstWebApp. In the default installation of WebLogic 7.0, you need to create the directories where your code and the Web application will live. For this example, create it in the sample directory that comes with WLS.

For Unix, do the following:

cd $WL_HOME/samples/server/config/examples/applications
mkdir -p firstWebApp/WEB-INF/src

For Windows, do this:

cd %WL_HOME%sampleserverconfigexamplesapplications
mkdir firstWebAppWEB-INFsrc

Now create the TLD file in the WEB-INF directory. Its contents will be Listing 18.10. Name it datetag.tld. Next, create the Java source file that will hold the tag library implementation. In the example, you created the class in the jspexample package. This directory structure must also exist for the source code.

For Unix, do this:

cd $WL_HOME/samples/server/config/examples/applications/firstWebApp/WEB-INF
mkdir -p src/jspexample

In Windows, do the following:

cd %WL_HOME%sampleserverconfigexamplesapplicationsfirstWebAppWEB-INF
mkdir srcjspexamples

In the src/jspexample directory, create the DateTag.java file. This code is shown in Listing 18.9.

To compile the Java source file into a Java class, do the following for Unix:

cd $WL_HOME/samples/server/config/examples/applications/firstWebApp/WEB-INF
mkdir classes
javac -d classes -classpath
$WL_HOME/server/lib/weblogic.jar src/jspexample/DateTag.java

Do this in Windows:

cd %WL_HOME%sampleserverconfigexamplesapplicationsfirstWebAppWEB-INF
mkdir classes
javac -d classes -classpath
%WL_HOME%serverlibweblogic.jar srcjspexampleDateTag.java

Tip

The javac command for each operating system should be on one line. It is wrapped for readability.

Now you need to create a web.xml file that will be used for the Web application. The web.xml file is the deployment descriptor for the Web application; it describes the Web application to WebLogic Server. It is the same file that you use when configuring a servlet in a Web application. For the sample JSP tag, it will look like Listing 18.12.

Example 18.12. web.xml

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
    "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

    <display-name>My First custom JSP tag</display-name>
    <description>
        This is a simple Web application to display some dynamic content via
        a custom JSP tag.
    </description>

    <taglib>
        <taglib-uri>datetag.tld</taglib-uri>
        <taglib-location>WEB-INF/datetag.tld</taglib-location>
    </taglib>

</web-app>

The other method for creating a tag library is to create a Java JAR file that contains the tag library class and TLD file. To do this, you need to create a temporary directory structure. Create a directory named example that contains the following:

example/
    jspexample/
        DateTag.class
        META-INF/
            datetag.tld

Then, from within the sample directory, run

jar cvf dateTagLibrary.jar jspexample

In the web.xml file for the Web application, modify the lines that reference the taglib as follows:

<taglib>
    <taglib-uri>datetag.tld</taglib-uri>
    <taglib-location>
        /WEB-INF/lib/dateTagLibrary.jar
    </taglib-location>
</taglib>

Tag libraries are commonly put into a JAR file to simplify delivery. You can easily deploy the JAR file into a different WebLogic Server by simply copying the JAR file into the appropriate directory.

Summary

The combination of JavaServer Pages, JavaBeans, and tag libraries creates a powerful tool in the J2EE toolbox. By separating the presentation logic in a JSP from the business logic in a JavaBean or Enterprise JavaBean, they help to improve the modularity and design of your application. A JSP page fits well into the “viewer” part of a Model-Controller-Viewer (MVC) design pattern and can cleanly interact with the controller and model parts, such as a tag library fronting an Enterprise JavaBean. By allowing programmers well versed in HTML to focus on their job without heavy Java programming, JavaServer Pages improve the productivity of both HTML programmers and Java programmers generating the JavaBeans or tag libraries.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset