ManagedCloud Servers

High performance handled and monitored by us 24/7/365. A complete solution to provide you with our in house expertise 24/7 tailored to your specific needs. We'll setup a bespoke server for your site using the latest tehnologies so you can get the most out of your hardware and get your website loading quickly and reliably. Find out more..

cPanelCloud Servers

Recommended - High performance cloud servers with no technical knowledge required. If you're hosting multiple websites already and you're looking to consolidate, or if you're looking to isolate yourself from the shared hosting environment but you don't have the time or knoweldge to manage a server, then the Managed cPanel Servers are for you. Find out more..

UnmanagedCloud Servers

Our unmanaged range gives you complete control at rock bottom prices and our cloud platform boasts super fast multipath 40Gb/s network, the latest Intel Xeon V3 CPUs and enterprise grade redundant SSDs. If you're a sysadmin look no further, we offer some of the best specification to price ratio servers available. Find out more..

Need Web Hosting? Try ours, it's fast, reliable and feature loaded with support you can depend on. From £1.60 / month.

View Plans

A Guide to Understanding, Writing and Running a Java Server Page

Java Server Pages is a technology for developing web pages that include dynamic content. With JSP, designers and developers can quickly incorporate dynamic content into web sites using Java and simple markup tags. The JSP platform lets the developer access data and Java business logic without having to master the complexities of Java application development.

A JSP page contains standard markup language elements, such as HTML tags, just like a regular web page. However, a JSP page also contains special JSP elements that allow the server to insert dynamic content in the page.

JSP was released during the time servlet technology had gained popularity as one of the best web technologies available. JSP is not meant to replace servlets, however. In fact, JSP is an extension of the servlet technology, and it is common practice to use both servlets and JSP pages in the same web applications.

Your First JSP

JavaServer Pages (JSPs) are, in the most basic sense, web pages with embedded Java code. The embedded Java code is executed on the server before the page is returned to the browser.

Follow the step by step instructions, you will learn how to write a simple JSP page and run it. Tomcat is used to run JSP applications.

Configuring Tomcat to Run a JSP Application
  1. Create the following JSP directory. C:\Program Files\Apache Group\Tomcat X.X\webapps\jjolt\jsp
  2. Add a subdirectory named WEB-INF under the jsp directory.
  3. Edit server.xml, the server configuration file, so Tomcat knows about this new JSP application. The server.xml file is located in the conf directory under C:\Program Files\Apache Group\Tomcat X.X. Right after the closing tag of the following block. html <Context path="/examples" docBase="examples" debug="0" reloadable="true"> <Logger className="org.apache.catalina.logger.FileLogger" prefix="localhost_examples_log." suffix=".txt" timestamp="true"/> </Context> Add the following code: html <Context path="/jsp" docBase="/jjolt/jsp" debug="0" reloadable="true"> </Context>html
  4. Since the configuration file has been changed, you have to restart Tomcat.
Writing a JSP File

A JSP page consists of standard HTML tags and Java code, like the code shown in HelloWorld.jsp. html <html> <body> <%out.println("Hello World!");%> </body> </html>

As you can see, the page is composed of standard HTML with a dash of Java contained between the <% and %> character sequences. The <% and %> along with the code inside is called a scriptlet.

Now, start your web browser, and type the following URL: http://localhost:8080/jsp/HelloWorld.jsp If successful you will see "Hello World" printed to your browser screen.

How JSP Works

Like most source code, JSP pages start life as text files and end up being compiled.

Inside the JSP container is a special servlet called the page compiler. The servlet container is configured to forward to this page compiler all HTTP requests with URLs that match the .jsp file extension.

When a .jsp page is first called, the page compiler parses and compiles the .jsp page into a servlet class. If the compilation is successful, the jsp servlet class is loaded into memory. On subsequent calls, the servlet class for that .jsp page is already in memory; however, it could have been updated. Therefore, the page compiler servlet will always compare the timestamp of the jsp servlet with the jsp page. If the .jsp page is more current, it will be recompiled.

So in a way, a JSP page is really just another way to write a servlet without having to be a Java programmer.

Implicit Objects

JSP container exposes a number of its internal objects to the page author. These are referred to as implicit objects, because their availability in a JSP page is automatic. The developer can assume that these objects are present and accessible via JSP scripting elements. JSP implicit objects are summarized below;.

page -- Pages servlet instance. config -- Servlet configuration data. request -- Request data, parameters. response -- Response data. out -- Output stream for page content. session -- User-specific session data. application -- Data shared by all application pages. pageContext -- Context data for page execution. exception -- Uncaught error or exception.

JSP Elements

For now, you have learned that a JSP page can have Java code and HTML tags. More formally, you can say that a JSP page has elements and template data. The elements, which also are called JSP tags, make up the syntax and semantics of JSP. Template data is everything else. Template data includes parts that the JSP container does not understand, such as HTML tags.

There are three types of JSP elements you can use: * directive elements * action elements * scripting elements

Directive Elements

The directive elements specify information about the page itself that remains the same between requests. Directives do not directly produce any output that is visible to end users when the page is requested; instead, they generate side effects that change the way the JSP container processes the page. Directives have the following syntax:

```html
<%@ directive attribute1="value1" attribute2="value2" ... %>
```
</code></pre>

Three types of directives are as follows: * Page directives * Include directives * Tag library directives

<h4>The Page Directive</h4>

The page directive is the most complicated JSP directive, primarily because it supports such a wide range of attributes and associated functionality. The basic syntax of the page directive is as follows: <code><%@ page attribute1="value1" attribute2="value2" ... %></code>

<h6>The Language Attribute</h6>

The language attribute specifies the language to be used in all scripting elements on the page. By default, the value is "java" and all JSP containers must support Java as the scripting language.

Here is how the language attribute is used to specify Java as the scripting language:

<pre><code> ``` <%@ page language="java" %> ```

Note: It does not have any effect on the generated servlet. In fact, this attribute is useful only in a JSP container that supports a language other than Java as the scripting language.
The info attribute

The info attribute allows the author to add a documentation string to the page that summarizes its functionality.

It can be retrieved later using the getServletInfo method. The JSP container then will create a getServletInfo method in the resulting servlet. This method returns the value of the info attribute specified in the page.

The import Attribute

The import attribute is similar to the import keyword in a Java class or interface. The attribute is used to import a class or an interface or all members of a package. You will definitely use this attribute often.

Whatever you specify in the import attribute of a page directive will be translated into an import statement in the generated servlet class. An example is given below:

```
  <%@ page import="java.util.*, java.awt.List" %>
```  
</code></pre>

<h6>The contenttype attribute</h6>

This attribute is used to indicate the MIME type of the response being generated by the JSP page. For example, the following directive tells the JSP container that the output should be sent using simplified Chinese characters: <code><%@ page contentType="text/html;charset=GB2312" %></code>

<h6>The pageEncoding attribute</h6>

The pageEncoding attribute provides an alternate means for specifying the character set used by the JSP page. Instead of supplying the character set as part of the contentType attribute’s value, it can be declared independently via the pageEncoding attribute, as in: <code><%@ page pageEncoding="ISO-8859-1" %></code>

<h6>The extends attribute</h6>

The extends attribute identifies the superclass to be used by the JSP container when it is translating the JSP page into a Java servlet. You should use this attribute with extra care. In most cases, you should not use this attribute at all. In Tomcat, the parent class that will be subclassed by the resulting servlet is HttpJspBase.

<h6>The session attribute</h6>

The session attribute is used to indicate whether or not a JSP page participates in session management. The following shows an example of the use of the session attribute:

<pre><code>```

<%@ page session="false" %> ```
The buffer attribute

The buffer attribute controls the use of buffered output for a JSP page. To turn off buffered output, so that all JSP content is passed immediately to the HTTP response, this attribute should be set to none, as follows: <%@ page buffer="none" %> Note that the JSP container has the discretion to use a buffer size larger than specified to improve performance.

The autoFlush attribute

The autoFlush attribute is related to the page buffer. When the value is set to "true", the JSP container will automatically flush the buffer when the buffer is full. If the value is "false", however, the JSP author needs to flush the buffer manually using the flush method of the JspWriter object, such as the following: out.flush(). For example, the following code specifies a false value for the autoFlush attribute: <%@ page autoFlush="false" %>

The isThreadSafe attribute

The isThreadSafe attribute is used to indicate whether your JSP page, once it is compiled into a servlet, is capable of responding to multiple simultaneous requests. When the value of this attribute is true, you guarantee that simultaneous access to this page is safe. However, you can assign "false" to this attribute as in the following code:

```
 <%@ page isThreadSafe="false" %>
```
</code></pre>

<h6>The errorPage attribute</h6>

The errorPage attribute specifies the URL of an error page that will be displayed if an uncaught exception occurs in this current JSP page. This alternate page is indicated by specifying a local URL as the value for this attribute, as in the following: <code><%@ page errorPage="/error.jsp" %></code>

<h6>The isErrorPage attribute</h6>

The isErrorPage attribute is used to mark a JSP page that serves as the error page for one or more other JSP pages. When this attribute is set to true, it indicates that the current page is intended for use as a JSP error page.

<h4>The include Directive</h4>

This directive enables JSP page authors to include the contents of other files in the current JSP page. The file to be included is identified via a local URL, and the directive has the effect of replacing itself with the contents of the indicated file. The syntax of the include directive is as follows:

<pre><code>``` <%@ include file="localURL" %> ``` </code></pre>

The include directive is useful if you have a common source that will be used by more than one JSP page. Instead of repeating the same code in every JSP page, thus creating a maintenance problem, you can place the common code in a separate file and use an include directive from each JSP page. The following is an example of how to include HTML files:

<pre><code>``` <%@ include file="/copyright.html" %> ``` </code></pre>

<h4>The taglib Directive</h4>

This directive is used to notify the JSP container that a page relies on one or more custom tag libraries. A tag library is a collection of custom tags that can be used to extend the functionality of JSP. Once this directive has been used to indicate the reliance of a page on a specific tag library, all of the custom tags defined in that library become available for use on that page. The syntax of this directive is as follows:

<pre><code>``` <%@ taglib uri="tagLibraryURI" prefix="tagPrefix" %>. ``` </code></pre>

<h3>Scripting Elements</h3>

Scripting elements enable developers to directly embed code in a JSP page, including code that generates output to appear in the results sent back to the user. There are three types of scripting elements:

<pre><code>* Declarations * Expressions * Scriptlets </code></pre>

<h5>Declarations</h5>

Declarations are used to define variables and methods specific to a JSP page. Declared variables and methods can then be referenced by other scripting elements on the same page. Declarations also provide a way to create initialization and clean-up code by utilizing the jspInit and jspDestroy methods. The syntax for declarations is:

<pre><code>``` <%! declaration(s) %> ``` </code></pre>

An example is given below:

<pre><code><%! String getTime() { return java.util.Calendar.getInstance().getTime().toString(); } %> <%! private int x = 0, y = 0; %> <% out.println("x = " + x + "y = " + y + "Time = " + getTime());%> </code></pre>

<h5>Expressions</h5>

The JSP expression element is explicitly intended for output generation. Expressions get evaluated when the JSP page is requested and their results are converted into a String and fed to the print method of the out implicit object. The syntax for this scripting element is as follows:

<pre><code>``` <%= expression %> ``` </code></pre>

An example is given below:

<pre><code>Current Time: <%= java.util.Calendar.getInstance().getTime() %> </code></pre>

<h5>Scriptlets</h5>

Scriptlets are the code blocks of a JSP page. The general syntax for scriptlets is:

<pre><code>``` <% scriptlet %> ``` </code></pre>

Here is an example of a scriptlet for database connection.

<pre><code><%@ page session="false" %> <%@ page import="java.sql.*" %> <% try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("JDBC driver loaded"); } catch (ClassNotFoundException e) { System.out.println(e.toString()); } %> </code></pre>

<h4>Comments</h4>

Three different ways can be used to insert comments into a JSP page.

<ul> <li>Content comments</li> </ul>

To write a comment that will be included in the output of a JSP page that is generating web content, the following syntax is used:

<pre><code>``` <!-- comment --> ``` Those familiar with HTML and XML will recognize that this is the standard comment syntax for those two markup languages. In this case, the comment is actually sent to the browser. </code></pre>

<ul> <li>JSP comments</li> </ul>

JSP comments are independent of the type of content being produced by the page. They are also independent of the scripting language used by the page. These comments can only be viewed by examining the original JSP file, the following syntax is used:

<pre><code>``` <%-- comment --%> ``` The body of this comment is ignored by the JSP container. JSP comments are useful for commenting out portions of a JSP page, as when debugging.

  • Scripting language comments

Comments may also be introduced into a JSP page within scriptlets, using the native comment syntax of the scripting language. Java, for example, uses /* comment */ as comment delimiters. With Java as the JSP scripting language, scripting language comments take the following form: <% /* comment */%> Like JSP comments, scripting language comments will not appear in the page’s output. Unlike JSP comments, though, which are ignored by the JSP container, scripting language comments will appear in the source code generated for the servlet.

Standard Action Elements

This section provides an overview of Standard Action elements. Standard action elements basically are tags that can be embedded into a JSP page. At compile time, they also are replaced by Java code that corresponds to the predefined task.

The following is the list of JSP standard action elements:

  • jsp:useBean
  • jsp:setProperty
  • jsp:getProperty
  • jsp:param
  • jsp:include
  • jsp:forward
  • jsp:plugin
  • jsp:params
  • jsp:fallback
  • jsp:include

The jsp:useBean, jsp:setProperty, and jsp:getProperty elements are related to Bean. The jsp:param element is used in the jsp:include, jsp:forward, and jsp:plugin elements to provide information in the name/value format.

UseBean

The <jsp:useBean> tag tells the page that we want to make a bean available to the page. The tag is used to create a bean or fetch an existing one from the server. Attributes of the tag specify the type of bean you wish to use and assign it a name. The <jsp:useBean> tag comes in two forms as follows. <jsp:useBean id="bean name" class="class name"/> Or <jsp:useBean id="bean name" class="class name"> Here's an example of the <jsp:useBean> tag. <jsp:useBean id="company" class="com.jm.company.Company"/>

GetProperty

The primary way to access a bean's properties in JSP is through the <jsp:getProperty> tag. Unlike the <jsp:useBean> tag which performs some work behind the scenes but doesn't produce any output, the <jsp:getProperty> tag actually produces content that we can see in the HTML generated by the page. The syntax is as follows:

<jsp:getProperty name="bean name" property="property name"/> Here's an example of using the <jsp:getProperty> tag to get the company name.
<jsp:useBean id="company" class="com.jm.company.Company"/>
<html>
<body>
The name of the company is: <jsp:getProperty name="company" property="name"/>
</body>
</html>
SetProperty

We use <jsp:setProperty> to modify the properties of beans. The <jsp:setProperty> tag can be used anywhere inside the JSP document after the bean has been defined with the <jsp:useBean> tag. The syntax is as follows: <jsp:setProperty name="bean name" property="property name"value="property value"/> Here’s an example of using the <jsp:setProperty> tag to set the company name.

<jsp:useBean id="company" class="com.jm.company.Company"/>
<jsp:setProperty name="company" property="name" value="JM Online Training"/>
Include

The <jsp:include> action element is used to incorporate static or dynamic resources into the current page. This action element is similar to the include directive, but jsp:include provides greater flexibility because you can pass information to the included resource.

The syntax is as follows: <jsp:include page="localURL" flush="flushFlag" /> If you want to pass information to the included resource, use the second syntax:

<jsp:include page="relativeURL" flush="true">
  ( <jsp:param . . . /> )*
</jsp:include>

In contrast, the JSP include directive does not automatically update the including page when the included file is modified.

Forward

The <jsp:forward> action is used to permanently transfer control from a JSP page to another location within the same web application. The syntax for the jsp:forward action element has two forms. For the jsp:forward element that does not have a parameter name/value pair, the syntax is as follows: <jsp:forward page="relativeURL"/> If you want to pass information to the included resource, use the syntax:

<jsp:forward page="relativeURL">
  ( <jsp:param . . . /> )*
</jsp:forward>

The page attribute represents the URL of the included resource in the local server.

Plug-in

The <jsp:plugin> action is used to generate browser-specific HTML for specifying Java applets which rely on the Sun Microsystems’ Java plug-in.

Params and fallback.

These two action elements can occur only as part of the <jsp:plugin> action

Custom Tags

Custom tags are the standard extension mechanism for JSP, and are among its newest features. A key advantage of JSP over many of the other commonly used dynamic content systems is its ability to separate presentation from implementation through the use of HTML-like tags. By avoiding the use of JSP elements that embed scripting language code in the page, maintenance of JSP pages is greatly simplified, and the opportunity to reuse the Java code that provides the underlying functionality is preserved. Custom tag libraries can be written to provide added functionality for a JSP application without having to resort to the use of Java code within your JSP pages.

On the other hand, custom tags are explicitly designed to add functionality to JSP pages, including the dynamic generation of page content such as HTML. If you need to generate HTML content programmatically via Java, custom tags are an ideal implementation technique. Custom tags can be used to insert text into the page, and also to implement flow of control. Attributes can be specified for custom tags, as parameters that influence their behaviour.

What is a Custom Tag?

A custom tag is a user-defined JSP language element. When a JSP page containing a custom tag is translated into a servlet, the tag is converted to operations on an object called a tag handler. The Web container then invokes those operations when the JSP page's servlet is executed.

Advantages of using custom tags.

  • Tags are reusable, which saves precious development and testing time.
  • Tags can be customized using attributes, either statically or dynamically.
  • Tags have access to all of the objects available to the JSP page, including request, response, and output variables.
  • Tags can be nested, which allows for more complex interactions within a JSP page.
  • Tags simplify the readability of a JSP page.

Your First Custom Tag

This section presents the step-by-step approach to building a JSP application that uses custom tags. 1. Create a TLD file named taglib.tld and save it in the WEB-INF directory under C:\Program Files\Apache Group\Tomcat X.X\webapps\jjolt.

  <? xml version="1.0" encoding="ISO-8859-1" ?>
    <!DOCTYPE taglib
              PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
              "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
      <taglib>
        <jsp-version>1.1</jsp-version>
        <tlibversion>1.0</tlibversion>
        <shortname></shortname>
        <tag>
          <name>myCustomTag</name>
          <tagclass>com.jjolt.MyCustomTag</tagclass>
        </tag>
      </taglib>
  1. Write and compile the Java class called MyCustomTag.java. Make sure that the .class file is located in the following directory. C:\Program Files\Apache Group\Tomcat X.X\webapps\jjolt\jsp\WEB-INF_ classes\com\jjolt directory.
      package com.jjolt;
      import javax.servlet.jsp.*;
      import javax.servlet.jsp.tagext.*;
        public class MyCustomTag extends TagSupport {
        public int doEndTag() throws JspException {
          JspWriter out = pageContext.getOut();
         try {
            out.println("Hello World.");
          }
          catch (Exception e) {
          }
          return super.doEndTag();
        }
      }
  1. Create a SimplePage.jsp file in the following directory. C:\Program Files\Apache Group\Tomcat X.X\webapps\jjolt\jsp <%@ taglib uri="/myTLD" prefix="mytag"%> <mytag:myCustomTag/>

Edit the deployment descriptor (web.xml) file. To use custom tags, you must specify a <taglib> element in your web.xml file. The <taglib> element must appear after the <servlet> and <servlet-mapping> if any. An example of the deployment descriptor is given bellow. <display-name>template</display-name> <taglib> <taglib-uri>/myTLD</taglib-uri> <taglib-location>/WEB-INF/taglib.tld</taglib-location> </taglib> 4. Restart Tomcat. Open your web browser and type http://localhost:8080/jjolt/jsp/SimplePage.jsp in the Address box. If sucessful you will see "Hello World" printed to your browser screen.

What just happened?

When the user requests the JSP page, the JSP container sees the <taglib> tag. Because of this, the JSP container knows that it is seeing a custom tag. It then: * Consults the deployment descriptor (web.xml) to find the location of the taglib where the URI is "/myTLD". The deployment descriptor returns the path to the TLD file. The JSP container will remember this path.

* Continues processing the next line and encounters the custom tag myCustomTag.      Having found out the name and location of the TLD file, the JSP container reads the TLD file and obtains the fully qualified name of the Java class for the tag myTag. That is com.jjolt.MyCustomTag. The JSP container can then load the class for the tag and start processing it.

Tag Library Descriptors

A tag library descriptor (TLD) is an XML document that describes a tag library. A TLD contains information about a library as a whole and about each tag contained in the library. TLDs are used by a Web container to validate the tags and by JSP page development tools.

TLD filenames must have the extension .tld. TLD files are stored in the WEB-INF directory or a subdirectory of WEB-INF. TLD must begin with an XML document prolog that specifies the version of XML and the document type definition (DTD):


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

A TLD file contains the <taglib> root element. This element can have the following subelements: * tlib-version: The tag library's version. * jsp-version: The jspversion element specifies the JSP version. The format is the same as the tlibversion element. * short-name: The shortname element specifies a short name for the tag library. * uri: The uri element specifies the link to an additional source of documentation for the tag library. * display-name: Optional name intended to be displayed by tools. * description: Optional tag-specific information. * listener: See Listener Element. * tag: See Tag Element.

The Tag Element

The tag element specifies a custom tag in the library. The subelements of tag are:

  • name: The unique tag name.
  • tag-class: The fully-qualified name of the tag handler class.
  • tei-class: Optional subclass of javax.servlet.jsp.tagext.TagExtraInfo.
  • body-content: The body content type.
  • display-name: Optional name intended to be displayed by tools.
  • small-icon: Optional small-icon that can be used by tools.
  • large-icon: Optional large-icon that can be used by tools.
  • description: Optional tag-specific information.
  • variable: Optional scripting variable information. See Providing Information About the Scripting Variable.
  • attribute: Tag attribute information.

The Listener Element

The Listener Element specifies event listeners for the tag library. The listeners are listed in the TLD as listener elements and the Web container will instantiate the listener classes and register them.

Custom Tag Syntax

<%@ taglib uri="tagLibraryURI" prefix="tagPrefix" %> * The uri attribute specifies an absolute or relative URI that uniquely identifies the tag library descriptor associated with this prefix. * The prefix attribute defines a string that will become the prefix to distinguish a custom action.

After you have defined the taglib directive, you can then use the custom tag. If the custom tag does not have a content body, you can use the custom tag with the following format. <prefix:tagName/> Otherwise, you can use the following format for a custom tag that has a content body: <prefix:tagName>body</prefix:tagName> You can pass attributes to the tag handler by specifying the attribute(s) in the custom tag, each with the following format: attributeName="attributeValue" An example of using the custom tag is given bellow. <mytag:myTag id="126" name="john"/> The tag has two attributes: id with the value of 126 and name with the value of john.

Tag Handlers

A tag handler is an object invoked by a Web container to evaluate a custom tag during the execution of the JSP page that references the tag. Tag handlers must implement either the Tag or BodyTag interface.

The JSP Custom Tag API

In JSP, the javax.servlet.jsp.tagext has four interfaces and twelve classes. The two most important interfaces are Tag and BodyTag. These two interfaces also set the life cycle of a tag handler. They are explained in details below.

The Tag Interface

The base requirement for custom tag handlers is that they implement the Tag interface. Tag handlers that implement the Tag interface must provide implementations for all the interface's methods. These methods are as follows: * doStartTag * doEndTag * getParent * setParent * setPageContext * release

You can write a tag handler by simply implementing the Tag interface and providing blank implementations of all its six methods. A simple example of the tag handler is shown below.

package com.jjolt;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class SimpleTagHandler implements Tag {
  public void setParent(Tag t) {
 }
  public void setPageContext(PageContext p) {
  }
  public void release() {
  }
  public Tag getParent() {
    return null;
  }
  public int doStartTag() {
    return EVAL_BODY_INCLUDE;
  }
  public int doEndTag() {
    return EVAL_PAGE;
  }
}
The BodyTag Interface

If the tag handler needs to interact with the body, the tag handler must implement BodyTag. Such handlers typically implement the doInitBody and the doAfterBody methods. These methods interact with body content passed to the tag handler by the JSP page's servlet. The following example shows a tag handler that manipulates the body content of a JSP custom tag. It converts a body content to uppercase and outputs it to the browser.

package com.jjolt;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class Capitalizer1Tag implements BodyTag {
  PageContext pageContext;
  BodyContent bodyContent;
  public void setParent(Tag t) {
  }
  public void setPageContext(PageContext pageContext) {
    this.pageContext = pageContext;
  }
  public void release() {
  }
  public Tag getParent() {
    return null;
  }
  public int doStartTag() {
    return EVAL_BODY_BUFFERED;
  }
  public void setBodyContent(BodyContent bodyContent) {
    this.bodyContent = bodyContent;
  }
  public void doInitBody() {
  }
  public int doAfterBody() {
    String content = bodyContent.getString();
    try{
      JspWriter out = bodyContent.getEnclosingWriter();
      out.print(content.toUpperCase());
    }
    catch(Exception e) {}
    return SKIP_BODY;
  }
  public int doEndTag() throws JspException {
    return EVAL_PAGE;
 }
}

The Support Classes

Although the interfaces of Tag and BodyTag provide a great way to write tag handlers, one apparent drawback is you must provide implementations for all the methods, including those you don't use. This makes the code look more complex than necessary. To solve this problem, the javax.servlet.jsp.tagext package provides support classes that implement those interfaces. These classes are TagSupport and BodyTagSupport. Now, instead of implementing an interface, you can extend one of these classes.

The TagSupport Class

The TagSupport class implements the IterationTag interface. It has the following signature. public class TagSupport implements IterationTag, java.io.Serializable The TagSupport class is intended to be used as the base class for tag handlers.

The BodyTagSupport Class

The BodyTagSupport class implements the BodyTag interface. It has the following signature. public class BodyTagSupport extends TagSupport implements BodyTag This class is meant to be subclassed by tag handlers that need to implement the BodyTag interface. To illustrate the usefulness of these support classes, we convert the above example using BodyTag to make use of BodyTagSupport class.

package com.jjolt;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class Capitalizer2Tag extends BodyTagSupport {
  public int doAfterBody() {
    String content = bodyContent.getString();
    try {
      JspWriter out = bodyContent.getEnclosingWriter();
      out.print(content.toUpperCase());
    }
    catch(Exception e) {}
    return SKIP_BODY;
  }
}

See how simple the tag handler has become. And it is much easier to write and debug.

Conclusion

Having gone through this guide, designers and developers can quickly incorporate dynamic content into web sites using Java and simple markup tags. The guide is easy to understand and implement.

Need Web Hosting? Try ours, it's fast, reliable and feature loaded with support you can depend on. From £1.60 / month.

View Plans