Recent comments

Poll

Highest Users

UserPoints
shamali4560
Mujtaba1310
Billy650
maoo_o540
Moin_iyan360

Who's new

  • usman911
  • shshzaib
  • HafizSohaib
  • savitadhiya
  • i_feel_4u

Current weather

Lahore

night-few
  • Few clouds
  • Temperature: 12 °C
  • Wind: West, 9.3 km/h
  • Pressure: 1015 hPa
  • Rel. Humidity: 54%
  • Visibility: 6 kilometers
Reported on:
Tue, 01/06/2009 - 18:25

Adsense

PerfSpot

Web Application Development with JSP and XML

Web Application Development with JSP and XML
Part I: Fast Track JSP

By Qusay H. Mahmoud

If you have had the opportunity to build Web applications using technologies such as Common Gateway Interface (CGI) and servlets, you are accustomed to the idea of writing a program to generate the whole page (the static and the dynamic part) using that same program. If you are looking for a solution in which you can separate the two parts, look no further. JavaServerTMPages (JSPTM) are here.

JSPs allow you to separate front-end presentation from business logic (middle and back-end tiers). It is a great Rapid Application Development (RAD) approach to Web applications. This series of articles provides a hands-on tutorial explaining how to develop modern Web applications for today

 

The Dynamic Web

The Web has evolved from a network-based hypermedia distributed information system offering static information to a marketplace for selling and buying goods and services. The increasingly sophisticated applications to enable this marketplace require a technology for presenting dynamic information.
First generation solutions included CGI, which is a mechanism for running external programs through a Web server. The problem with CGI scripts is scalability; a new process is created for every request.
Second generation solutions included web server vendors providing plug-ins and APIs for their servers. The problem is that their solutions were specific to their server products. For example, Microsoft provided Active Server Pages (ASP) that made it easier to create dynamic content. However, their solution only worked with Microsoft IIS or Personal Web Server. Therefore, if you wanted to use ASP you had to commit yourself to Microsoft products and you would not be enjoying the freedom of selecting your favorite web server and operating system!
Another second generation technology that is quite popular in enterprise computing is Java servlets. Servlets make it easier to write server-side applications using Java technology. The problem with either CGI or servlets, however, is that you have to follow the write, compile, and deploy life cycle.
JSPs are a third generation solution that can be combined easily with some second generation solutions, creating dynamic content, and making it easier and faster to build Web-based applications that work with a variety of other technologies: web servers, web browsers, application servers and other development tools.
JavaServer Pages (JSP)
JSPs are an open, freely available specification developed by Sun Microsystems as an alternative to Microsoft's Active Server Pages (ASP) technology, and a key component of the JavaTM2 Enterprise Edition (J2EETM) specification. Many of the commercially available application servers (such as BEA WebLogic, IBM WebSphere, Live JRun, Orion, and so on) already support JSP.
JSP vs. ASP
JSP and ASP deliver similar functionality. They both use tags to allow embedded code in an HTML page, session tracking, and database connection. Some of the trivial differences are:
  • ASPs are written in VBScript and JSPs are written in Java. Therefore, JSPs are platform-independent and ASPs are not.
  • JSPs use JavaBeansTMtechnology as the component architecture and ASPs use ActiveX components.
Beyond these trivial differences, there are a number of important differences that may help you in choosing a technology for your organization:
  • Speed and Scalability: Although ASPs are cached, they are always interpreted. By contrast, JSPs are compiled into Java servlets and loaded into memory the first time they are called, and executed for all subsequent calls. This gives JSPs speed and scalability advantage over ASPs.
  • Extensible Tags: JSPs have an advanced feature known as extensible tags. This mechanism enables developers to create custom tags. In other words, extensible tags allow you to extend the JSPs tag syntax. You cannot do this with ASPs.
  • Freedom of Choice: Unless you install Chili!Soft ASP, ASPs work only with Microsoft IIS and Personal Web Server. Using ASPs requires a commitment to Microsoft products, while JSPs do not tie you to any specific web server or operating system. JSPs are becoming a widely supported standard.
For a more detailed comparison between JSPs and ASPs, see Comparing JSP and ASP.

 

Software Environment

To run JSP pages, you need a web server with a web container that conforms to JSP and servlet specifications. The web container executes on the web server and manages the execution of all JSP pages and servlets running on that web server. Tomcat 3.2.1 is a complete reference implementation for the Java Servlet 2.2 and JSP 1.1 specifications. Download and install binary versions of Tomcat.
To configure Tomcat:
  • Set the environment variable JAVA_HOME to point to the root directory of your JavaTM2 Standard Edition (J2SETM) installation.
  • Set the TOMCAT_HOME environment variable to point to the root directory of your Tomcat installation.
  • To start Tomcat, use TOMCAT_HOME/bin/startup.bat for windows or startup.sh for UNIX.
    By default, it will start listening on port 8080.
  • Save your .jsp files in TOMCAT_HOME/webapps/examples/jsp and your JavaBeans classes in TOMCAT_HOME/webapps/examples/web-inf/classes .


Note: If you work under Windows, you may get an Out of space environment error when you try to start Tomcat. There are two ways to fix this: either change the initial memory setting of the DOES window to a value greater than 3200 OR edit the config.sys file and add the following line: SHELL=c:\PATHTO\command.com /E:4096


How JSP Pages Work
A JSP page is basically a web page with traditional HTML and bits of Java code. The file extension of a JSP page is ".jsp" rather than ".html" or ".htm", and that tells the server that this page requires special handling that will be accomplished by a server extension or a plug-in. Here is a simple example:
Sample 1:date.jsp
<HTML>
<HEAD>
<TITLE>JSP Example</TITLE>
</HEAD>
<BODY BGCOLOR="ffffcc">
<CENTER>
<H2>Date and Time</H2>
<%java.util.Date today = new java.util.Date();
out.println("Today's date is: "+today);%>
</CENTER>
</BODY>
</HTML>
This example contains traditional HTML and some Java code. The tag <% identifies the beginning of a script, and the %> tag identifies the end of a script. When date.jsp is requested from a Web browser, you see something similar to Figure 1.

Figure 1: Requesting date.jsp
Behind the Scenes
When this page (date.jsp) is called, it will be compiled (by the JSP engine) into a Java servlet. At this point the servlet is handled by the servlet engine just like any other servlet. The servlet engine then loads the servlet class (using a class loader) and executes it to create dynamic HTML to be sent to the browser, as shown in Figure 2. For this example, the servlet creates a Date object and writes it as a string to the out object, which is an output stream to the browser.

Figure 2: Request/Response Flow when Calling a JSP
The next time the page is requested, the JSP engine executes the already-loaded servlet unless the JSP page has changed, in which case it is automatically recompiled into a servlet and executed.
Scripting Elements
In the date.jsp example the full Date class name is used including the package name, which may become tedious. If you want to create an instance of Date simply by using: Date today = new Date(); without having to specify the full class path use the page directive as follows:
Sample 2:date2.jsp
<%@page import="java.util.*" %>
 
<HTML>
 <HEAD>
 <TITLE>JSP Example</TITLE>
 </HEAD>
 <BODY BGCOLOR="ffffcc">
 <CENTER>
 <H2>Date and Time</H2>
 <%
 java.util.Date today = new java.util.Date();
 out.println("Today's date is: "+today);
 %>
 </CENTER>
 </BODY>
 </HTML>
 
Yet, another way of doing the same thing using the <%= tag is by writing:
Sample 3:date3.jsp
 
<%@page import="java.util.*" %>
 <HTML>
 <HEAD>
 <TITLE>JSP Example</TITLE>
 </HEAD>
 <BODY BGCOLOR="#ffffcc">
 <CENTER>
 <H2>Date and Time</H2>
 Today's date is: <%= new Date() %>
 </CENTER>
 </BODY>
 </HTML>

 As you can see, the same thing can be accomplished using different tags and techniques. There are several JSP scripting elements. Here are some conventional rules that will help you use JSP scripting elements effectively:

  • Use <% ... %> to handle declarations, expressions, or any other type of valid snippet of code. Sample 1 above is an example.
  • Use the page directive as in <%@page ... %> to define the scripting language (the default is Java). Also, it can be used to specify import statements. Here is an example:
    <%@page language="java" import="java.util.*" %> .
  • Use <%! .... %> to declare variables or methods. For example:
    <%! int x = 10; double y = 2.0; %> .
  • Use <%= ... %> to define an expression and cast the result as a String . For example:
    <%= a+b %> or <%= new java.util.Date() %> .
  • Use the include directive as in <%@ include ... %> to insert the contents of another file in the main JSP file. For example:
    <%@include file="copyright.html" %> .
Handling Forms
One of the most common parts of e-commerce applications is an HTML form where the user enters some information such as name and address. Using JSP, the form's data (the information the user enters in the form) gets stored in the request object that is sent from the browser to the JSP container. The request is processed and the result is sent through the response object back to the browser. These two objects are implicitly available to you.
To demonstrate how to handle HTML forms using JSP, here is an example form with two fields: one for name and the other for email. As you can see, the HTML form is defined in a JSP source file. The request.getParameter method is being used to retrieve data from the form into variables created using JSP tags.
The process.jsp page prints either a form or the information provided by the user depending on the values of the form's fields. If the form's values are null the form is displayed, otherwise, the information provided by the user is displayed. Note that the form is created and being handled by code in the same JSP file.
Sample 4:process.jsp
 
<HTML>
<HEAD>
<TITLE>Form Example</TITLE>
</HEAD>
<BODY BGCOLOR="#ffffcc">
<% if (request.getParameter("name")==null && request.getParameter("email") == null) { %>
<CENTER>
<H2>User Info Request Form</H2>
<FORM METHOD="GET" ACTION="process.jsp">
<P>
Your name: <input type="text" name="name" size=26>
<P>
Your email: <input type="text" name="email" size=26>
<P>
<input type="submit" value="Process">
</FORM>
</CENTER>
<% } else { %>
<%! String name, email; %>
<%
name = request.getParameter("name");
email = request.getParameter("email");
%>
<P>
<B>You have provided the following info</B>:
<P>
<B>Name</B>: <%= name %><P>
<B>Email</B>: <%= email %>
<% } %>
</BODY>
</HTML>
 
If process.jsp is requested from a web server, you see something similar to Figure 3.

Figure 3: process.jsp loaded
Enter your name and email and click on Process to submit the form for processing, and you see something similar to Figure 4.

Figure 4: Form is processed
Reusable Components
The above example form is simple in the sense that there is not much code involved. When more code is involved, then it is important not to mix business logic with front end presentation in the same file. Separating business logic from presentation permits changes to either side without affecting the other. However, production JSP code should be limited to front end presentation. So, how do you implement the business logic part?
That is where JavaBeans come in to play. This technology is a portable, platform-independent component model that lets developers write components and reuse them everywhere. In the context of JSP, JavaBeans contain business logic that returns data to a script on a JSP page, which in turn formats the data returned from the JavaBean component for display by the browser. A JSP page uses a JavaBean component by setting and getting the properties that it provides.
What are the Benefits
There are several benefits to using JavaBeans to augment JSP pages:
  • Reusable components: different applications will be able to reuse the components.
  • Separation of business logic and presentation logic: you can change the way data is displayed without affecting business logic.
  • Protecting your intellectual property by keeping source code secure.
Example: Using JavaBeans with JSP
Now, let's see how to modify the process.jsp example above to use JavaBeans. In the above form these are two fields: name and email . In JavaBeans, these are called properties. So, first you write a JavaBean component with setX and getX methods, where X is the property name. For example, if you have get and set methods: setName and getName then you have a property known as name . Sample 5 shows a FormBean component.
Good components must be able to interoperate with other components from different vendors. Therefore, to achieve component reuse, there are two important rules (which are imposed by the JavaBeans architecture) to follow:
  1. Your bean class must provide a constructor with no arguments so it can be created using Beans.instantiate .
  2. Your bean class must support persistence by implementing the interface Serializable or Externalizable .
Sample 5:FormBean.java
package userinfo;
 import java.io.*;
 public class FormBean implements Serializable {
  private String name;
  private String email;
  public FormBean() {
   name = null;
   email = null;
  }
  public void setName(String name) {
   this.name = name;
  }
  public String getName() {
   return name;
  }
  public void setEmail(String email) {
   this.email = email;
  }
  public String getEmail() {
   return email;
  }
 }

In order to use the FormBean component in the JSP file, you need to instantiate the bean component. This is done using the <jsp:useBean> tag. The next line <jsp:setProperty> is executed when the bean is instantiated, and used to initialize the bean's properties. In this case, both properties ( name and email ) are set using a single statement. Alternatively, it is possible to set the properties one at a time, but first you need to retrieve the form's date. Here is an example of how you would set the name property:

 
<%! String yourname, youremail; %>
 <% yourname = request.getParameter("name"); %>
 <jsp:setProperty name="formbean" property="name" value="<%=yourname%>"/>

Once the properties have been initialized with data retrieved from the form, property values are retrieved for presentation using <jsp:getProperty> in the else part, as shown in Sample 6.

Sample 6:process2.jsp
 
<jsp:useBean id="formbean" class="userinfo.FormBean"/>
 <jsp:setProperty name="formbean" property="*"/>
 <HTML>
 <HEAD>
 <TITLE>Form Example</TITLE>
 </HEAD>
 <BODY BGCOLOR="#ffffcc">
 <% if (request.getParameter("name")==null && request.getParameter("email") == null) { %>
 <CENTER>
 <H2>User Info Request Form </H2>
 <form method="GET" action="process2.jsp">
 <P>
 Your name: <input type="text" name="name" size=27>
 <p>
 Your email: <input type="text" name="email" size=27>
 <P>
 <input type="submit" value="Process">
 </FORM>
 </CENTER>
 <% } else { %>
 <P>
 <B>You have provided the following info</B>:
 <P>
 <B>Name</B>: <jsp:getProperty name="formbean" property="name"/>
 <P>
 <B>Email</B>: <jsp:getProperty name="formbean" property="email"/>
 <% } %>
 </BODY>
 </HTML>
 
Conclusion
Developers interested in developing quality production web applications should familiarize themselves with technologies that are applicable not only for today's market but tomorrow's as well, namely JSP and XML. The J2EE BluePrints program from Sun provides a combination of design guidelines and sample applications to get you up to speed quickly. www.java.sun.com/j2ee/blueprints The next article will show how to create your own JSP tags; discuss the capabilities that the JSP technology provides that are ideally suited for working with XML; and show you how to effectively use JSP with XML. JSP and XML make an excellent combination for web applications that share information, because JSPs have XML support built right into them in the form of JSP tag libraries. Stay tuned for more information on this in the next article in this series.
 

abid's picture

nice work

 

ABid

gemind's picture

    Web Application

 

 
Web Application Development with JSPTM and XML
Part III: Developing JSP Custom Tags


By Qusay H. Mahmoud
August 2001

 

JavaServer PagesTM (JSPTM) technology makes it easy to embed bits of JavaTM code (or scriptlets) in HTML documents. This solution, however, may not be suitable for all HTML content developers, perhaps because they do not know Java and they do not care to learn its syntax. While JavaBeans can be used to encapsulate much of the Java code, using them in JSP pages still requires content developers to have some knowledge of Java syntax.
JSP technology allows you to introduce new custom tags through the tag library facility. As a Java developer, you can extend JSP pages by introducing custom tags that can be deployed and used in an HTML-like syntax. Custom tags also allow you to provide better packaging by improving the separation between business logic and presentation logic.
This article presents a brief overview of custom tags, then it shows:
 
  • How to develop and deploy simple tags
  • How to develop and deploy advanced tags: parameterized tags and tags with a body
  • How to describe tags with the Tag Library Descriptor (TLD)
Finally, some programming guidelines are also provided.
 
Overview of Tags
If you have experience with HTML, you already know about the types of tags that can be used. Basically there are two types of tags, and both can have attributes (information about how the tag should do its job):
 
  • Bodyless Tags: A bodyless tag is a tag that has a start tag but does not have a matching end tag. It has the syntax:
 
<tagName attributeName="value"
anotherAttributeName="anotherValue"/>
Bodyless tags are used to represent certain functions, such as presenting an input field, or displaying an image. Here is an example of a bodyless tag in HTML:
<IMG SRC="/articles/content/JSP-XML3/fig10.gif">
 
  • Tags with a Body: A tag with a body has a start tag and a matching end tag. It has the syntax:
 
<tagName attributeName="value"
anotherAttributeName="anotherValue">
...tag body...
</tagName>
Tags with a body are used to perform operations on the body content, such as formatting. Here is an example of a tag with a body in HTML:
<H2>Custom Tags</H2>
 
 
JSP Custom Tags
JSP custom tags are merely Java classes that implement special interfaces. Once they are developed and deployed, their actions can be called from your HTML using XML syntax. They have a start tag and an end tag. They may or may not have a body. A bodyless tag can be expressed as:
<tagLibrary:tagName />
And, a tag with a body can be expressed as:
 
<tagLibrary:tagName>
   body
</tagLibrary:tagName>
Again, both types may have attributes that serve to customize the behavior of a tag. The following tag has an attribute called name, which accepts a String value obtained by evaluating the variable yourName:
<mylib:hello name="<%= yourName %>" />
Or, it can be written as a tag with a body as:
 
<mylib:hello>
 <%= yourName %>
</mylib:hello>
 


Note: Any data that is a simple string, or can be generated by evaluating a simple expression, should be passed as an attribute and not as body content.


 
Benefits of Custom Tags
 
A very important thing to note about JSP custom tags is that they do not offer more functionality than scriptlets, they simply provide better packaging, by helping you improve the separation of business logic and presentation logic. Some of the benefits of custom tags are:
 
  • They can reduce or eliminate scriptlets in your JSP applications. Any necessary parameters to the tag can be passed as attributes or body content, and therefore no Java code is needed to initialize or set component properties.
  • They have simpler syntax. Scriptlets are written in Java, but custom tags can be used in an HTML-like syntax.
  • They can improve the productivity of nonprogrammer content developers, by allowing them to perform tasks that cannot be done with HTML.
  • They are reusable. They save development and testing time. Scritplets are not reusable, unless you call cut-and-paste reuse.
In short, you can use custom tags to accomplish complex tasks the same way you use HTML to create a presentation.
 
Defining a Tag
A tag is a Java class that implements a specialized interface. It is used to encapsulate the functionality from a JSP page. As we mentioned earlier, a tag can be bodyless or with a body. To define a simple bodyless tag, your class must implement the Tag interface. Developing tags with a body is discussed later. Sample 1 shows the source code for the Tag interface that you must implement:
Sample 1: Tag.java
 
public interface Tag {
   public final static int SKIP_BODY = 0;
   public final static int EVAL_BODY_INCLUDE = 1;
   public final static int SKIP_PAGE = 5;
   public final static int EVAL_PAGE = 6;
 
   void setPageContext(PageContext pageContext);
   void setParent(Tag parent);
   Tag getParent();
   int doStartTag() throws JspException;
   int doEndTag() throws JspException;
   void release();
}
All tags must implement the Tag interface (or one of its subinterfaces) as it defines all the methods the JSP runtime engine calls to execute a tag. Table 1 provides a description of the methods in the Tag interface.
 
Table 1: Description of methods in the Tag interface
Method
Description
setPageContext(PageContext pc)
This method is invoked by the JSP runtime, prior to doStartTag, to set the page context.
setParent(Tag parent)
Invoked by the JSP runtime, prior to doStartTag, to pass a tag handler a reference to its parent tag.
getParent
Returns a Tag instance that is the parent of this tag.
doStartTag
Invoked by the JSP runtime to prompt the tag handler to process the start tag for this instance.
doEndTag
Invoked by the JSP runtime after returning from doStartTag. The body of the action may or may not have been evaluated, depending on the return value of doStartTag.
release
Invoked by the JSP runtime to indicate to the tag handler to perform any cleanup necessary.
My First Tag
Now, let's look at a sample tag that when invoked prints a message to the client.
There are a few steps involved in developing a custom tag. These steps can be summarized as follows:
1.       Develop the tag handler
2.       Create a tag library descriptor
3.       Test the tag
1. Develop the Tag Handler
A tag handler is an object invoked by the JSP runtime to evaluate a custom tag during the execution of a JSP page that references the tag. The methods of the tag handler are called by the implementation class at various points during the evaluation of the tag. Every tag handler must implement a specialized interface. In this example, the simple tag implements the Tag interface as shown in Sample 2.
Sample 2: HelloTag.java
 
package tags;
 
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
 
public class HelloTag implements Tag {
   private PageContext pageContext;
   private Tag parent;
 
   public HelloTag() {
      super();
   }
 
   public int doStartTag() throws JspException {
      try {
         pageContext.getOut().print(
         "This is my first tag!");
      } catch (IOException ioe) {
         throw new JspException("Error:
         IOException while writing to client"
         + ioe.getMessage());
      }
      return SKIP_BODY;
   }
 
   public int doEndTag() throws JspException {
      return SKIP_PAGE;
   }
 
   public void release() {
   }
 
   public void setPageContext(PageContext
   pageContext) {
      this.pageContext = pageContext;
   }
 
   public void setParent(Tag parent) {
      this.parent = parent;
   }
 
   public Tag getParent() {
      return parent;
   }
}
The two important methods to note in HelloTag are doStartTag and doEndTag. The doStartTag method is invoked when the start tag is encountered. In this example, this method returns SKIP_BODY because a simple tag has no body. The doEndTag method is invoked when the end tag is encountered. In this example, this method returns SKIP_PAGE because we do not want to evaluate the rest of the page; otherwise it should return EVAL_PAGE.
To compile the HelloTag class, assuming that Tomcat is installed at: c:\tomcat:
  • Create a new subdirectory called tags, which is the name of the package containing the HelloTag class. This should be created at: c:\tomcat\webapps\examples\web-inf\classes.
  • Save HelloTag.java in the tags subdirectory.
  • Compile with the command:
 
c:\tomcat\webapps\examples\web-inf\classes\tags>
javac -classpath c:\tomcat\lib\servlet.jar
HelloTag.java
2. Create a Tag Library Descriptor
The next step is to specify how the tag will be used by the JSP runtime that executes it. This can be done by creating a Tag Library Descriptor (TLD), which is an XML document. Sample 3 shows a sample TLD:
Sample 3: mytaglib.tld
 
<?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">
 
<!-- a tag library descriptor -->
 
<taglib>
   <tlibversion>1.0</tlibversion>
   <jspversion>1.1</jspversion>
   <shortname>first</shortname>
   <uri></uri>
   <info>A simple tab library for the
   examples</info>
 
 <tag>
    <name>hello</name>
    <tagclass>tags.HelloTag</tagclass>
    <bodycontent>empty</bodycontent>
    <info>Say Hi</info>
 </tag>
</taglib>
First we specify the tag library version and JSP version. The <shortname> tag specifies how we are going to reference the tag library from the JSP page. The <uri> tag can be used as a unique identifier for your tag library.
In this TLD, we only have one tag named hello whose class is specified using the <tagclass> tag. However, a tag library can have as many tags as you like. The <bodycontent> tells us that this tag will not have a body; otherwise an error will be produced. On the other hand, if you like to evaluate the body of the tag, that value would be:
  • tagdependent: meaning that any body of the tag would be handled by the tag itself, and it can be empty.
  • JSP: meaning that the JSP container should evaluate any body of the tag, but it can also be empty.
Save mytaglib.tld in the directory: c:\tomcat\webapps\examples\web-inf\jsp.
3. Test the Tag
The final step is to test the tag we have developed. In order to use the tag, we have to reference it, and this can be done in three ways:
1.       Reference the tag library descriptor of an unpacked tag library. For example:
 
<@ taglib uri="/WEB-INF/jsp/mytaglib.tld"
prefix="first" %>
2.       Reference a JAR file containing a tag library. For example:
 
<@ taglib uri="/WEB-INF/myJARfile.jar"
prefix='first" %>
3.       Define a reference to the tag library descriptor from the web-application descriptor (web.xml) and define a short name to reference the tag library from the JSP. To do this, open the file: c:\tomcat\webapps\examples\web-inf\web.xml and add the following lines before the end line, which is <web-app>:
 
<taglib>
       <taglib-uri>mytags</taglib-uri>
       <taglib-location>/WEB-INF/jsp/
       mytaglib.tld</taglib-location>
    </taglib>
Now, write a JSP and use the first syntax. Sample 4 shows an example:
Sample 4: Hello.jsp
 
<%@ taglib uri="/WEB-INF/jsp/mytaglib.tld"
 prefix="first" %>
<HTML>
<HEAD>
<TITLE>Hello Tag</TITLE>
</HEAD>
 
<BODY bgcolor="#ffffcc">
 
<B>My first tag prints</B>:
 
<first:hello/>
 
</BODY>
</HTML>
The taglib is used to tell the JSP runtime where to find the descriptor for our tag library, and the prefix specifies how we will refer to tags in this library. With this in place, the JSP runtime will recognize any usage of our tag throughout the JSP, as long as we precede our tag name with the prefix first as in <first:hello/>.
Alternatively, you can use the second reference option by creating a JAR file. Or, you can use the third reference option simply by replacing the first line in Sample 4 with the following line:
 
<%@ taglib uri="mytags" prefix="first" %>
Basically, we have used the mytags name, which was added to web.xml, to reference the tag library. For the rest of the examples in this article, this reference will be used.
Now, if you request Hello.jsp from a browser, you would see something similar to Figure 1.
 

Figure 1: First Custom Tag
The custom tag developed in Sample 4 is a simple tag, the goal of it was just to give you a flavor of the effort involved in developing custom tags. You may have noticed that even this simple tag required us to implement a number of methods, some of which have very simple implementations. To minimize the effort involved, the JSP designers provided a template to be used for implementing simple tags. The template is the TagSupport abstract class. It is a convenience class that provides default implementations for all the methods in the Tag interface.
Therefore, an easier way to write simple tags is to extend the TagSupport class rather than implementing the Tag interface. You can think of the TagSupport abstract class as an adapter. Having said that, the HelloTag class in Sample 4 can be easily written as shown in Sample 5.
Sample 5: Extending the TagSupport class
 
package tags;
 
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
 
public class HelloTag extends TagSupport {
 
   public int doStartTag() throws JspException {
      try {
         pageContext.getOut().print("This is my
         first tag!");
      } catch (IOException ioe) {
         throw new JspException("Error:
         IOException while writing
        to client" + ioe.getMessage());
      }
      return SKIP_BODY;
   }
 
   public int doEndTag() throws JspException {
      return SKIP_PAGE;
   }
}
Parameterized Tags
We have seen how to develop simple tags. Now, let's see how to develop parameterized tags--tags that have attributes. There are two new things that that need to be added to the previous example to handle attributes:
1.       Add a set method
2.       Add a new tag to mytagslib.tld
Adding a set method and changing the output message results in Sample 5.
Sample 5: A tag with an attribute
 
package tags;
 
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
 
public class HelloTagParam extends TagSupport {
   private String name;
 
   
   public void setName(String name) {
      this.name = name;
   }
   
 
   public int doStartTag() throws JspException {
      try {
         pageContext.getOut().print("Welcome to
         JSP Tag Programming, " +name);
      } catch (IOException ioe) {
         throw new JspException("Error:
         IOException
         while writing to client");
      }
      return SKIP_BODY;
   }
 
   public int doEndTag() throws JspException {
      return SKIP_PAGE;
   }
}
The next thing we need to do is add a new tag to mytaglib.tld. The new tag is shown in Sample 6. This snippet of code should be added to mytaglib.tld right before the last line, </taglib>:
Sample 6: revising mytaglib.tld
 
<tag>
 <name>helloparam</name>
 <tagclass>tags.HelloTagParam</tagclass>
 <bodycontent>empty</bodycontent>
 <info>Tag with Parameter</info>
 <attribute>
    <name>name</name>
     <required>false</required>
     <rtexprvalue>false</rtexprvalue>
         </attribute>
</tag>
We have added a new tag named helloparam. Notice the new <attribute> tag, which specifies that the helloparam tag accepts an attribute whose name is name. The <required> tag is set to false, meaning that the attribute is optional; the <rtexprvalue> tag is set to false specifying that no run time evaluation will be done.
Nothing needs to be added to the web.xml web-application descriptor file since we are using the same tag library: mytaglib.tld.
Now, we can test the new tag. The source code in Sample 7 shows how to test it using a name attribute "JavaDuke".
Sample 7: HelloTagParam.jsp
 
<%@ taglib uri="mytags" prefix="first" %>
<HTML>
<HEAD>
<TITLE>Hello Tag with Parameter</TITLE>
</HEAD>
 
<BODY bgcolor="#ffffcc">
<B>My parameterized tag prints</B>:
 
<P>
 
<first:helloparam name="JavaDuke"/>
 
</BODY>
</HTML>
If you request HelloTagParam.jsp from a web browser, you would see an output similar to that in Figure 2.
 

Figure 2: Testing a parameterized tag
Tag Libraries
A tag library is a collection of JSP custom tags. The Jakarta Taglibs Project provides several useful tag libraries for XML parsing, transformations, email, databases, and other uses. They can be easily downloaded and used.
Here we develop our tag library. As an example, we develop a simple math library that provides two tags, one for adding two numbers, and the other for subtracting one number from another number. Each tag is represented by one class. The source code for the two classes, Add.java and Subtract.java, is shown in Sample 8.
Sample 8: Add.java and Subtract.java
 
package tags;
 
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
 
public class Add extends TagSupport {
   private int num1, num2;
 
   public void setNum1(int num1) {
      this.num1 = num1;
   }
 
   public void setNum2(int num2) {
      this.num2 = num2;
   }
 
 
   public int doStartTag() throws JspException {
      try {
         pageContext.getOut().print("Welcome
         to First
          Grade Math! ");
         pageContext.getOut().print("The sum of: " +
         num1 + " and " + num2 + " is: " + (
         num1+num2));
      } catch (IOException ioe) {
         throw new JspException("Error:
         IOException
          while writing to client");
      }
      return SKIP_BODY;
   }
}
 
// Subtract.java
 
package tags;
 
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
 
public class Subtract extends TagSupport {
   private int num1, num2;
 
   public void setNum1(int num1) {
      this.num1 = num1;
   }
 
   public void setNum2(int num2) {
      this.num2 = num2;
   }
 
 
   public int doStartTag() throws JspException {
      try {
         pageContext.getOut().print("Welcome to First
          Grade Math! ");
         pageContext.getOut().print("If you
         subtract:
          " + num2 + " from " + num1 +
          ", you get: "+ (num1 - num2));
      } catch (IOException ioe) {
         throw new JspException("Error:
          IOException
         while writing to client");
      }
      return SKIP_BODY;
   }
}
The source code is easy to understand. Notice one thing we have repeated in Add.java and Subract.java is the call to pageContext.getOut.print. A better way to do this would be to get a JspWriter object then then use it to print to the client:
 
JspWriter out = pageContext.getOut();
out.print("first line");
out.print("second line");
The next step is to revise the tag library descriptor file, mytaglib.tld, and add descriptions to the two new tags. Sample 9 shows the description for the new tags. Add the following snippet of XML to mytaglib.tld, right before the last line.
Sample 9: revising mytaglib.tld
 
<tag>
    <name>add</name>
    <tagclass>tags.Add</tagclass>
    <bodycontent>empty</bodycontent>
    <info>Tag with Parameter</info>
    <attribute>
       <name>num1</name>
       <required>true</required>
       <rtexprvalue>false</rtexprvalue>
    </attribute>
    <attribute>
      <name>num2</name>
      <required>true</required>
      <rtexprvalue>false</rtexprvalue>
    </attribute>
 </tag>
 
 <tag>
    <name>sub</name>
    <tagclass>tags.Subtract</tagclass>
    <bodycontent>empty</bodycontent>
    <info>Tag with Parameter</info>
    <attribute>
       <name>num1</name>
       <required>true</required>
       <rtexprvalue>false</rtexprvalue>
    </attribute>
    <attribute>
      <name>num2</name>
      <required>true</required>
      <rtexprvalue>false</rtexprvalue>
    </attribute>
 </tag>
As you can see, each tag requires two attributes that must be named num1 and num2.
Now, we can test our math tag library using the test driver shown in Sample 10.
Sample 10: math.jsp
 
<%@ taglib uri="mytags" prefix="math" %>
<HTML>
<HEAD>
<TITLE>Hello Tag with Parameter</TITLE>
</HEAD>
 
<BODY bgcolor="#ffffcc">
<B>Calling first tag</B>
<P>
<math:add num1="1212" num2="121"/>
<P>
<B>Calling second tag</B>
<P>
<math:sub num1="2123" num2="3"/>
 
</BODY>
</HTML>
If you request math.jsp from a web browser, you would see an output that is similar to Figure 3.
 

Figure 3: Testing the math tag library
Tags with a Body
A tag handler for a tag with a body is implemented differently depending on whether the body needs to be evaluated once or multiple times.
  • Single Evaluation: if the body needs to be evaluated once, the tag handler should implement the Tag interface, or extend the TagSupport abstract class; the doStartTag method needs to return EVAL_BODY_INCLUDE, and if it does not need to be evaluated at all then it should return BODY_SKIP.
  • Multiple Evaluation: if the body needs to be evaluated multiple times, the BodyTag interface should be implemented. The BodyTag interface extends the Tag interface and defines additional methods (setBodyContent, doInitBody, and doAfterBody) that enable a tag handler to inspect and possibly change its body. Alternatively, and similarly to the TagSupport class, you can extend the BodyTagSupport class, which provides default implementations for the methods in the BodyTag interface. Typically, you need to implement doInitBody and doAfterBody methods. The doInitBody is called after the body content is set but before it is evaluated, and the doAfterBody is called after the body content is evaluated.
Single Evaluation
Here is an example of single evaluation where we extend the BodyTagSupport class. This example reads the body content, converts it to lowercase, then writes the output back to the client. Sample 11 shows the source code. The body content is retrieved as a string, converted to lowercase, then written back to the client.
Sample 11: ToLowerCaseTag.java
 
package tags;
 
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
 
public class ToLowerCaseTag extends BodyTagSupport {
 
   public int doAfterBody() throws JspException {
      try {
         BodyContent bc = getBodyContent();
         // get the bodycontent as string
         String body = bc.getString();
         // getJspWriter to output content
         JspWriter out = bc.getEnclosingWriter();
         if(body != null) {
            out.print(body.toLowerCase());
         }
      } catch(IOException ioe) {
         throw new JspException("Error:
         "+ioe.getMessage());
      }
      return SKIP_BODY;
   }
}
The next step is to add a tag to the tag library descriptor file, mytaglib.tld. The new tag descriptor is:
 
<tag>
 <name>tolowercase</name>
 <tagclass>tags.ToLowerCaseTag</tagclass>
 <bodycontent>JSP</bodycontent>
 <info>To lower case tag</info>
</tag>
Note that when you write a tag with a body, the <bodycontent> tag's value must be either JSP or jspcontent, as discussed earlier.
A test driver for this example is shown in Sample 12.
Sample 12: lowercase.jsp
 
<%@ taglib uri="mytags" prefix="first" %>
<HTML>
<HEAD>
<TITLE>Body Tag</TITLE>
</HEAD>
 
<BODY bgcolor="#ffffcc">
 
<first:tolowercase>
Welcome to JSP Custom Tags Programming.
</first:tolowercase>
 
</BODY>
</HTML>
If you request lowercase.jsp from a web browser, you would see something similar to Figure 4.
 

Figure 4: Testing the lowercase tag
 
Multiple Evaluations
Let's now see an example of a body tag evaluated multiple times. The example accepts a string and prints the string as many times as indicated in the JSP. The source code is shown in Sample 13:
Sample 13: LoopTag.java
 
package tags;
 
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
 
public class LoopTag extends BodyTagSupport {
 
   int times = 0;
 
   BodyContent bodyContent;
 
   public void setTimes(int times) {
 
      this.times = times;
   }
 
   public int doStartTag() throws JspException {
      if (times>0) {
        return EVAL_BODY_TAG;
      } else {
         return SKIP_BODY;
      }
   }
 
   public void setBodyContent(BodyContent
   bodyContent) {
      this.bodyContent = bodyContent;
   }
 
   public int doAfterBody() throws JspException {
      if (times >1) {
        times--;
        return EVAL_BODY_TAG;
      } else {
         return SKIP_BODY;
      }
   }
 
   public int doEndTag() throws JspException {
      try {
         if(bodyContent != null) {
           bodyContent.writeOut(
           bodyContent.getEnclosingWriter());
         }
      } catch(IOException e) {
        throw new JspException(
        "Error: "+e.getMessage());
      }
      return EVAL_PAGE;
   }
}
In this example, the methods implemented play the following roles:
  • The doStartTag method gets called at the start of the tag. It checks if the loop needs to be performed.
  • The setBodyContent is called by the JSP container to check for more than one loop.
  • The doAfterBody method is called after each evaluation; the number of times the loop needs to be performed is decreased by one, then it returns SKIP_BODY when the number of times is not greater than one.
  • The doEndTag method is called at the end of the tag, and the content (if any) is written to the enclosing writer.
Similarly to previous examples, the next step is to add a new tag descriptor to mytaglib.tld. The following lines show what needs to be added:
 
<tag>
 <name>loop</name>
 <tagclass>tags.LoopTag</tagclass>
 <bodycontent>JSP</bodycontent>
 <info>Tag with body and parameter</info>
 <attribute>
     <name>times</name>
     <required>true</required>
     <rtexprvalue>true</rtexprvalue>
 </attribute>
</tag>
Note that the <rtexprvalue> tag specifies that evaluations will be performed at runtime.
A test driver is shown in Sample 14.
Sample 14: loops.jsp
 
<%@ taglib uri="mytags" prefix="first" %>
<HTML>
<HEAD>
<TITLE>Body Tag</TITLE>
</HEAD>
 
<BODY bgcolor="#ffffcc">
 
<first:loop times="4">
Welcome to Custom Tags Programming.<BR>
</first:loop>
 
</BODY>
</HTML>
Finally, if you request loops.jsp from a browser, you would see output similar to that in Figure 5.
 

Figure 5: Testing loops.jsp
Programming Guidelines
Here are a few guidelines to keep in mind when developing JSP tag libraries:
  • Keep it simple: if a tag requires several attributes, try to break it up into several tags.
  • Make it usable: consult the users of the tags (HTML developers) to achieve a high degree of usability.
  • Do not invent a programming language in JSP: do not develop custom tags that allow users to write explicit programs.
  • Try not to reinvent the wheel: there are several JSP tag libraries available, such as the Jakarta Taglibs Project. Check to see if what you want is already available so you do not have to reinvent the wheel.
Conclusion
In Web Application Development with JSP and XML Part II: JSP with XML in mind, we have seen how to parse XML documents. But even the untrained eye would have noticed that we have embedded lots of the parsing (or logic) code in JSP. Even though we have used JavaBeans to encapsulate much of the Java code, we still ended up with JavaServer Pages mixing program logic with presentation.
Custom tags help you improve the separation of program logic (parsing and iteration in Part II), and presentation. The various examples in this article show how to develop and deploy simple and advanced custom tags. As an exercise, you may want to rewrite the SAX and DOM examples in Part II as tag libraries. Also, you may wish to look at what the Jakarta Taglibs Project has to offer for XML parsing and XSL transformations. It provides tag libraries for other things as well.
 
For more information
 
About the author
Qusay H. Mahmoud provides Java consulting and training services. He has published dozens of articles on Java, and is the author of Distributed Programming with Java (Manning Publications, 1999).
 
 

 

 


 

WaQaR Aziz
BITF03 - Alumini 
Director Software Development -- Pentasoft inc.

 


 

 

gemind's picture

   

 

 

gemind's picture

  Web Application

 

 

Web Application Development with JSP and XML
Part II: JSP with XML in mind

By Qusay H. Mahmoud

 

 

The Extensible Markup Language (XML) has become the de facto standard data representation format for the Internet. XML data can be processed and interpreted on any platform--from handheld device to mainframe. It a perfect companion for Java applications that need portable data.

 

Java is the winner programming language to use with XML. Most XML parsers are written in Java, and it provides a comprehensive collection of Java APIs specifically targeted at building XML-based applications. JavaServer PagesTM (JSPTM) technology has access to all this since it can use the full power of the Java platform to access programming language objects to parse and transform XML documents. JSP has been designed with XML in mind; you can write a JSP page as an XML document!

This article presents a brief overview of XML, then it shows how to:

 

  • Present XML documents
  • Generate XML using JSP
  • Parse XML documents using Simple Access API for XML (SAX) and Document
  • Object Model (DOM)
  • Use SAX and DOM in JSP
  • Transform XML into other markup languages

 

Overview of XML

XML is a metalanguage used to define documents containing structured data. The features and benefits of XML can be grouped in the following major areas:

 

  • Extensibility: as a metalanguage, XML can be used to create its own markup languages. Many XML-based markup languages exist today, including the Wireless Markup Language (WML).
  • Precise structure: HTML suffers from loose structures and that makes it difficult to process HTML documents effectively. On the other hand, XML documents are well structured; each document has a root element and all elements must be nested within other elements.
  • Two document types: there are two main XML document types
    1. Valid document: a valid XML document is defined by a Document Type Definition (DTD), which is the grammar of the document that defines what kind of elements, attributes, and entities may be in the document. The DTD defines the order as well as the occurrence of elements.
    2. Well-Formed document: a well-formed XML document does not have to adhere to a DTD. But it must follow two rules: 1) each element must have an open tag and a close tag. 2) there must be one root element that contains all other elements.
  • Powerful extensions: as we mentioned earlier, XML is used to define syntax only. In other words, it is used to define content. To define the semantics, style, or presentation you need to use the Extensible Stylesheet Language (XSL). Note that a document may have multiple stylesheets that can be used by different users.



Note: A well-formed document is handy if the document is simple, or when processing simple structures over networks where bandwidth is a concern, since it does not have the overhead of a complex DTD.

 

XML versus HTML

XML and HTML are both markup languages, where tags are used to annotate data. The main differences are:

  • In HTML, the syntax and semantics of the document are defined. HTML alone can be used to create a visible presentation to the user. XML allows you to define document syntax.
  • HTML documents are not well-formed. For example, not all tags are closed with a matching tag. XML documents are well-formed.
  • Tag names are case sensitive in XML, but not in HTML.

Let's look at an XML document. The following example is a sample XML document, from a fictitious quote server, representing a portfolio of stocks. As you can see, there is one root element (portfolio), and every element has a start tag and a close tag.

Sample 1: stocks.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<portfolio>
  <stock>
    <symbol>SUNW</symbol>
    <name>Sun Microsystems</name>
    <price>17.1</price>
  </stock>
  <stock>
    <symbol>AOL</symbol>
    <name>America Online</name>
    <price>51.05</price>
  </stock>
  <stock>
    <symbol>IBM</symbol>
    <name>International Business Machines</name>
    <price>116.10</price>
  </stock>
  <stock>
    <symbol>MOT</symbol>
    <name>MOTOROLA</name>
    <price>15.20</price>
  </stock>
</portfolio>

The first line of Sample 1 states the XML version number, which is 1; and lets the processor know that the encoding scheme to be used is "UTF-8".

Although this is a simple document, it contains useful information that can be processed easily since it is well structured. For example, the stock server may want to sort the portfolio, in a specific order, based on the price of stocks.

 

Presenting XML Documents

 

XML documents contain portable data. This means that the example in Sample 1 can be processed for output to different browsers (desktop browser for the PC, microbrowser for the handheld device). In other words, an XML document can be transformed into HTML or WML or any other markup language.

If you load the stocks.xml document in a browser that supports XML (such as Microsoft's IE), you would see something similar to Figure 1.


Figure 1: stocks.xml in a browser

Basically, the browser has parsed the document and displayed it in a structured manner. But, this is not really useful from a user's point of view. Users want to see data displayed as useful information in a way that is easy to navigate.

One way to display XML documents nicely is to apply a transformation on the XML document, either to extract the data or create a new format (such as transforming XML data to HTML). This transformation can be done using a transformation language such as the Extensible Stylesheet Language Transformation (XSLT), which is part of XSL. XSL allows you to write XML vocabulary for specifying formatting semantics. In other words, there are two parts to XSL, which is part of the World Wide Web Consortium (W3C) Style Activity:

  • Transformation language (XSLT)
  • Formatting language (XSL formatting objects)

The XSL stylesheet in Sample 2 performs the required transformation for the portfolio element. It generates HTML markup and extracts data from the elements in the stocks.xml document.

Sample 2: stocks.xsl

 

<?xml version="1.0"?>

<xsl:stylesheet version="1.0" xmlns:xsl=
"http://www.w3.org/TR/WD-xsl">

<xsl:template match="/">
<html>
<head>
<title>Stocks</title>
</head>
<body bgcolor="#ffffcc" text="#0000ff">
<xsl:apply-templates/>
</body>
</html>
</xsl:template>

<xsl:template match="portfolio">

<table border="2" width="50%">
<tr>
<th>Stock Symbol</th>
<th>Company Name</th>
<th>Price</th>
</tr>
<xsl:for-each select="stock">
&lttr>
 <td>
   <i><xsl:value-of select=
   "symbol"/></i>
 </td>
<td&