Using a JSP Tag Library

JSP is an efficient mechanism for providing presentation content, which is mainly the look-and-feel view of the application. Putting too much logic in a JSP makes your application brittle and not easy to change. A custom tag library can be developed to provide a clean separation of presentation logic (usually handled by Java developers) and presentation content (displaying the application's data, which is usually handled by page designers). To accomplish this goal, the JSP architecture provides a set of standard taglibs (refer to the “Standard JSP Actions (Taglibs)” section earlier). In this section, you'll learn how to develop your own taglib to customize your application.

A taglib, or tag handler, is a Java class that either extends the TagSupport (or BodyTagSupport) class, or implements the Tag (or BodyTag) interface of the javax.servlet.jsp.tagext package. The taglib class must react to the Web container callback methods. Therefore, it must implement the doStartTag(), which is called when the tag starts, and the doEndTag() method, which is called when the tag ends.

You use a tag to produce output or to define new objects that can be referenced and used as scripting variables in the JSP page. The following is a simple example of a JSP that uses a taglib to display a personalized greeting message to the student after she has logged in to enroll for courses:

<%@ taglib uri="/welcome" prefix="student" %>
<HTML>
  <BODY>
    <student:welcome userId="remo"/>
  </BODY>
</HTML>

This JSP will display a personalized message:

Welcome back <Full student name>. It's <date and time>
					

In the example, the tag name is identified by the prefix student and the suffix welcome. No other attributes or scripting variables are used in this simple tag.

The following lists the supporting taglib class WelcomeTag.java, which extends the TagSupport class and implements the callback methods doStartTag() and doEndTag():

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.TagSupport;
import java.util.Date;
import java.io.IOException;
public class WelcomeTag extends TagSupport {
   public void setUserId (String userId) {
         id=userId;
   }
   public String getUserId () {
        return id;
   }
   public int doStartTag() throws JspException {
      try {
        JspWriter out = pageContext.getOut();
        String dateStr = new Date().toString();
        out.print("Welcome back "+ getName(id));
        out.println(". It's " + dateStr);
      } catch (Exception e) {
         e.printStackTrace();
         throw new JspException(e.getMessage());
      }
      return(EVAL_BODY_INCLUDE);
   }
   private String getName(String userId){
      // this can call a data source to get the real name
      return name;
   }
   private String id;
   private String name = "Raymond Ghaly";
}

The tag handler must implement setter and getter methods for each attribute, similar to those found in a JavaBean component (see the next section). The setUserId() and getUserId() methods are used to set and get the id attribute. The first letter of the attribute is capitalized after the get/set word in the method name. The Web container uses these methods to inform the tag handler instance of the attribute values before the doStartTag() or doAfterBody() method is invoked.

In the preceding example, the Web container calls the doStartTag() method, and returns a personalized welcome page for the userIdremo”. The doStartTag() returns the EVAL_BODY_INCLUDE constant, meaning to evaluate the tag's body content, and any subtags. Other valid constants returned by the doStartTag() are SKIP_BODY (tag contents will be ignored) and EVAL_BODY_TAG (evaluate the tag contents). Similarly, SKIP_PAGE and EVAL_PAGE are valid constants for the doEndTag() callback.

In deploying a taglib, you need to write a Tag Library Descriptor (TLD) file (WEB-INF/tlds/welcome.tld). A TLD is an XML file that declares each attribute for the tag within the <tag> element using an <attribute> tag for each attribute. The tag attributes allow the JSP page to pass String values into the tag handler, which can be used to configure the tag behavior.

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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>
  <tlib-version>1.0</tlib-version>
  <jsp-version>1.2</jsp-version>
  <short-name>student</short_name>
  <description>Welcome Tag for Students. Author: Raymond Ghaly</description>
  <tag>
    <name>welcome</name>
       <tagclass>WelcomeTag</tagclass>
     <attribute>
         <name>userId</name>
         <required>true</required>
         <rtexprvalue>true</rtexprvalue>
     </attribute>
  </tag>
</taglib>

As a part of a Web application, a taglib must be included in the Web deployment descriptor file web.xml, as follows:

<web-app>
   ...
  <taglib>
    <taglib-uri>/welcome</taglib-uri>
    <taglib-location>/WEB-INF/tlds/welcome.tld</taglib-location>
  </taglib>
  ...
</web-app>

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

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