Switch to standard view 
  Sybase logo
 
 
 



Accessing Web DataWindows with JSP using Custom tags

Authors:
Scott McReynolds (Example code)
     Sybase Advanced Solutions Group
Greg Douglas  (Documentation)
     Sybase Internet Applications Division

Overview

Java Server Pages (JSP) provides an environment to create dynamic web page content using HTML tags embedded with JSP tags to provide business logic using Java.  This paper outlines the steps needed to create a custom JSP tag extension to handle a DataWindow object.  A completed example is provided as a PowerJ project.

Introduction

JSPs provide server side preparation of dynamic content for delivery to client browsers.  This is accomplished through the use of HTML, the presentation of the page, and JSP tags, that determine the behavior and assembly of a JSP page. The JSP tag provides access to the implementation logic and data access.  There are three ways to handle Java implementation code within a JSP page:

Writing inline Java code is NOT recommended.  It is better to keep the presentation separate from the implementation. JSP provides for this model by using JavaBeans and custom tags.  Since JavaBeans are very reusable, i.e. they may be used by non-web base applications, they should never contain code that generates HTML output.  Custom tags on the other hand, while reusable, are web application specific.  Custom tags are a bridge between the presentation of the page and the implementation logic of the application. Custom tags can call JavaBean or EJB components.  This separation allows an advance web page designer to create pages using tags instead of having to learn Java, and the Java developer to focus on the implementation.  This will provide a cleaner and more manageable n-tier web application.

This paper we will focus on creating a DataWindow tag that can be used on a JSP page to return a DataWindow to a clients browser.  To create a custom tag you need to create two basic elements: a Java class that implements the tag logic, and a tag library descriptor (TLD) file.

Let's take a look at our example DataWindow tag code, and then create a PowerJ project that contains all the pieces for deployment.  There are numerous resources that discuss JSPs, custom tags and TLDs in detail, see reference section.

The DataWindow tag

This example consists of three elements: the JSP page, the TLD (tag library descriptor), and the DataWindowTag class.

The JSP page

Figure 1 shows the DataWindow JSP page.  Notice that there is a mix of HTML and JSP tags.  The page directive tells the JSP container how to process the page.  The JSP taglib uri tag tells the page where to find the custom tag definition and allows you to provide a unique prefix to use with the tag.

The custom tag is referenced by the prefix:tagname: j2ee:DataWindow.  The tag is followed by tag arguments that are passed to the tag class.  The arguments could be populated by a web form or programmatically assigned.  Notice that there is no Java code here, it is located in the custom tag object.

Note: Be sure to change the path to the custtest1.pbl, which uses the easdemodb database.

<HTML>
<HEAD><TITLE>
DataWindow Example JSP
</TITLE></HEAD>
<BODY>
<%-- Page Directives --%>
<%@ page language="java" buffer="8kb" import="DataWindow.*" 
    autoFlush="true" isThreadSafe="true" isErrorPage="false"  %>

<%@ taglib uri="WEB-INF/tlds/taglib.tld" prefix="j2ee" %>

<H1>
DataWindowJSP Example
</H1> 

<j2ee:DataWindow
      libName="C:\\DemoProjects\\PowerbuilderProjects\\custtest1.pbl"
      dwName="d_customer_list"
      allowForm="true"
      clientValidation="true"
      clientEvents="true"
      clientScriptable="true"
      clientFormatting="true"
      dbms="ODBC"
      dbparm="UseContextObject='No',ConnectString='DSN=EAS Demo DB V3;UID=dba;PWD=sql'"
      lock=""
      logid="jagadmin"
      logpass=""
      database=""
      servername=""
      selfLink="DataWindowJSP.jsp"
      selfLinkArg=""
      action=""
      context=""
      argument=""
      dwHtmlObjectName="dwTest"
      />
      </BODY></HTML>

    

Figure 1 - Example JSP Page

The Tag Library Descriptor (TLD)

When a JSP page loads for the first time and encounters the taglib uri tag, it loads the TLD file to determine the custom tag definition. The author of the custom tag must create the TLD file, which is in XML format. Figure 2 shows an example of the TLD. 

The first bold text shows the location of the Document Type Definition (dtd), which determines the structure of the TLD XML file. Notice the dtd located at the SUN site, this is the web wide definition of a TLD file.

The important part of the TLD is the <tag>. It defines the tag name used in the JSP page and maps it to the java class that handles the tag implementation. Associated with a tag are attributes. The attribute tag identifies the attribute name, whether it is required or optional, and rtexprvalue determines whether the value fixed or assigned.

 

<?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 tab library descriptor -->

<taglib>
  <tlibversion>1.0</tlibversion>
  <jspversion>1.1</jspversion>
  <info>
        DataWindow Custom Tag
  </info>

  <!-- insert tag -->
  <tag>
    <name>DataWindow</name>
    <tagclass>com.demo.jsp.DataWindowTag</tagclass>
    <bodycontent>JSP</bodycontent>
    <info>
        The Datawindow Tag
    </info>

    <attribute>
      <name>libName</name>
      <required>true</required>
      <rtexprvalue>true</rtexprvalue>
    </attribute>
       ........
       ........
  </tag>
</taglib>
Figure 2 - Example Tag Library Descriptor

The Tag Class (Handler)

The Tag class implements the functionality of the tag. Tag classes extend javax.servlet.jsp.tagext.TagSupport. TagSupport requires the following methods:

The doStartTag() method calls the getGenerator() method, which connects to the HTMLGenerator component within EAServer and returns a reference to the object. DataWindow attributes are set by the attributes passed to the tag handler. The DataWindow Generate() method is called to create the client output in the form of a JavaScript representation of the DataWindow.

import org.omg.CORBA.*;
import DataWindow.*;
import SessionManager.*;

public class DataWindowTag extends javax.servlet.jsp.tagext.TagSupport
{
    /* Setter and Getter Methods for setting the Datawindow parameters*/
        
    public String getArgument() {
        return _argument;
    }
    public void setArgument(String newValue) {
        _argument = newValue;
    }
     .....
     .....  

  public int doStartTag()
    {
        try{

        // Call method to get referance to the HTMLGenerator object in EAServer
        HTMLGenerator comp = this.getGenerator();

        // Set Datawindow parameters
        comp.SetDWObject( _libName, _dwName );
        comp.SetWeight(_allowForm, _clientValidation, _clientEvents, _clientScriptable, _clientFormatting);
        comp.SetHTMLObjectName(_dwHtmlObjectName);
        comp.SetTrans(_dbms, _dbparm, _lock, _logid, _logpass, _database, _servername);
        comp.SetSelfLink( _selfLink, _selfLinkArg);

        System.out.println("doStartTag _argument = " + _argument);
                if (_argument.equals(""))
                {
                        System.out.println("doStartTag blank _argument ");
                        comp.Retrieve();
                } else
                {
                        System.out.println("doStartTag nonblank _argument ");
                        comp.RetrieveEx(_argument);
                }

                // See if any client actions have been issued
                // (ie. next, previous, insert, etc.)

                if (_action.equals("") == false) 
                {
                        System.out.println("_action.equals == false ");

                        // there is some action
                        // Tell the DW Generator about the action (Next, Previous, Insert, etc.)
                        int ret_val = comp.SetAction(_action, _context);

                        if ( ret_val < 0 ) {
                                pageContext.getOut().println(comp.GetLastErrorString());
                        }
                        }

                        pageContext.getOut().println("Here is the generated DataWindow...");

                        //Generate the JavaScript representation of the DataWindow
                        pageContext.getOut().println(comp.Generate());

        } catch (Exception e){
            System.out.println("DataWindowTag: Error in doStartTag: " + e);
        }

        return EVAL_BODY_INCLUDE;
    }
    /**
     * doEndTag Method
     */

    public int doEndTag() throws JspTagException
    {
         return EVAL_PAGE;
    }
   /* Method makes call to the HTMLGenerator component in EAS

   */
   private HTMLGenerator getGenerator()
    {
        java.util.Properties props = new java.util.Properties();
        props.put("org.omg.CORBA.ORBClass","com.sybase.CORBA.ORB");
        ORB orb = ORB.init((String[]) null, props);

        Manager manager = ManagerHelper.narrow(orb.string_to_object("iiop://0:0"));
        Session session = manager.createSession("jagadmin", "");
        Factory factory = FactoryHelper.narrow(session.lookup("DataWindow/HTMLGenerator"));
        HTMLGenerator comp = HTMLGeneratorHelper.narrow(factory.create());
        return comp;    
    }
    ....
    ....

Figure 3 - Example Tag Class

When the JSP page is accessed: the taglib descriptor is loaded, the tag prefix is set, and the custom tag is used to access the DataWindow as specified by its attributes. As discussed above, the taglib.tld references the tag class to use, which in turn implements the tags logic with the attributes. The DataWindow tag returns the output show in Figure 4.

Figure 4 - Example DataWindow Tag Output

Creating a Custom Tag in PowerJ

This section will discuss how the PowerJ DataWindow Custom Tag example is configured. This is not a step by step discussion, but rather an outline of how to configure a PowerJ project to build a custom JSP tag for deployment to EAServer. Refer to the attached PowerJ example dw_jsp.

Note: rmc - right mouse click

Open PowerJ and create a new workspace. Open the View window. Menu View | Workspace

Create a Java Class target to implement the custom tag.

Now add the methods doStartTag() and doEndTag() to the class. Remember, the JSP container automatically calls these two methods.

Now that the tag class is created and compiled, it needs to be deployed as part of a JSP web application. A Web Application, a specification of J2EE, contains all resources of that web application, i.e. images, html pages, JSP pages, documents, JavaBeans and class files, etc. The Web Application is deployed to the JSP container as a WAR file or Web Application Archive file (actually a JAR file). A Web Application has a specific directory hierarchy as shown below in Figure 5.

Figure 5 - Web Application Hierarchy: From Development with JSP- Fields & Kolb


Notice that class files are located in WEB-INF/classes. The tag class must be placed there. So we need to tell PowerJ where to place the class file relative to the web application. This is done by:

The class is created. Now the class name and the arguments are known, you create the tablib descriptor. Create a text file and enter your specifications. Use the tablib.tld in the example as a template.

Next we create the JSP page. PowerJ has a JSP target type to create a basic JSP shell.

By default, PowerJ creates a JSP file with simple loop counter routine. Edit or cut and paste code for the JSP file to create your JSP page as shown in Figure 1. 

Now that the WAR target is created we can add the tag class target as a dependency to the WAR target. Adding a target as a dependency to a WAR target includes it as part of the web application for deployment. 

One more item, add the taglib.tld to the WAR file so it can be deploy with the web application. According to the Web Application hierarchy, all tablibs must go into the WEB-INF/tlds folder. Since the folder does not exist:

The project is ready for deployment.

The deployed files are located in the EAServer Repository: %Jaguar%\Repository\WebApplication\Appname

The figure 6 shows the View window of PowerJ listing the targets and files used in this example.

Figure 6 - PowerJ View Window

TagSupport Template

As part of this project, there is template target, TagSupport that models the basic TagSupport class. You can use it as a PowerJ template by:

Expanded Example - Master/Detail DataWindow

In addition to the tutorial example, there is a Master Detail DataWindow example as part of this PowerJ Project. The JSP targets are:

To deploy this example, do Run | Deploy and select EmployeeFrameAll. Remember to change the file path to point where you placed the custtest1.pbl, in DeptMaster and DeptDetail. Figure 7 shows the output.

Figure 7 Master/Detail DataWindow

The Dept ID link was defined in the DataWindow pbl. Figure 8 shows the definition of the link set for the dept_id column of the DataWindow.

Figure 8 Link definitions for dept_id

Link defines the JSP page to be called. Link Target indicates which frame of the frame set to use. Link Arguments says, get the column value from dept_id as a string and assign it to deptid, which is the page parameter to pass.

Summary

JSP is akin to server-side scripting, but more efficient and extendable. JSPs are text files with traditional HTML syntax combined with embedded Java code. However, it is good practice to minimize or avoid placing Java code directly into a JSP page, but rather create JavaBeans or tag extensions to handle the core business logic. This allows advance web designers to design complex pages without having to know Java. Tag Extensions allow the designer/programmer to create functionality that could not be achieved with standard HTML or JavaScript. It also allows you to build extensions that are specific to your applications, and not rely on fixed extensions built by a vendor.

While all the functionality for DataWindow manipulation is not present in this example, it is a foundation on which to build a more comprehensive tag library.

References:

http://www.taglib.com/
http://java.sun.com/products/jsp/
http://java.sun.com/products/jsp/docs.html
http://java.sun.com/products/jsp/faq.html
http://www.burridge.net/jsp/jspinfo.html
http://jakarta.apache.org/
http://java.sun.com/j2ee/




Back to Top
© Copyright 2010, Sybase Inc.