Passing Parameters with Custom Tags

   

Java™ 2 Primer Plus
By Steven Haines, Steve Potts

Table of Contents
Chapter 24.  Custom Tag Libraries


One of the areas where custom tags have an advantage over JavaBeans is in passing parameters. With JavaBeans, you normally set the values of the bean's class variables before invoking the method that you want to call. This is an effective, if somewhat cumbersome, way to pass parameters.

Custom tags, on the other hand, are allowed to pass parameters in a more direct fashion. The basic syntax for passing parameters to custom tags is

 <jpp:stringTag2 attr1="val1" attr2="val2" \> 

The name of the attribute is followed by the =, and then the value of the attribute in quotes. Providing support for these attributes is simple also. All you have to do is add methods to the implementing class in the form:

 public void setAttr1(String value1)  {     ... do something with this attribute's value ...  } 

Note

graphics/01icon18.gif

The name of the attribute is normally lowercase in the tag. The set() method name will always include a capitalized version of this name following the word "set."


The taglib must also reflect the existence of the attribute. It must provide a name, whether it is a required field, and whether it can be an expression.

Listing 24.7 shows a taglib that contains attributes.

Listing 24.7 The jppticket-taglib.tld
 <?xml version="1.0" encoding="UTF-8" ?>   <!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>  <!-- after this the default space is          "http://java.sun.com/j2ee/dtds/jsptaglibrary_1_2.dtd"     -->  <tlibversion>1.0</tlibversion>  <jspversion>1.1</jspversion>  <shortname>jpptaglib</shortname>  <info>     A tag library from Java Primer Plus  </info>  <tag>  <name>ticketTag</name>  <tagclass>com.samspublishing.jpp.ch25.TicketTag</tagclass>   <bodycontent>empty</bodycontent>  <info>a Hello World custom tag example</info>  <attribute>     <name>param1</name>     <required>true</required>  </attribute>  </tag>  </taglib> 

In most ways, this taglib is identical to the others that we have created. The only difference is in the addition of the attribute. To process an attribute, the attribute tag must be added.

 <attribute>     <name>param1</name>     <required>true</required>  </attribute> 

The implementing class must contain a method to handle the parameter param1 when it is passed in. Listing 24.8 shows the Java class file for this example.

Listing 24.8 The TicketTag.java Class
 /*   * TicketTag.java   *   * Created on July 13, 2002, 12:38 PM   */  package com.samspublishing.jpp.ch25;  import javax.servlet.jsp.*;  import javax.servlet.jsp.tagext.*;  import java.io.*;  /**   *   * @author  Stephen Potts   * @version   */  public class TicketTag extends TagSupport  {     private String param1;     public int doStartTag()     {        try        {           JspWriter out = pageContext.getOut();           out.print("The parameter that you entered = " + param1);        }catch (Exception e)         {            System.out.println("Error in TicketTag class" + e);        }        return(SKIP_BODY);     }     public void setParam1(String id)     {        this.param1=id;     }  } 

We added a set method for the parameter. The name of the method will be setXXX () where XXX is the name of the parameter. In this case, the name of the parameter is setParam1() because our parameter name is param1.

 public void setParam1(String id)  {     this.param1=id;  } 

This populates the private member variable called param1. Then, we use this variable in the output for this tag.

 out.print("The parameter that you entered = " + param1); 

The JSP file for this example is shown in Listing 24.9.

Listing 24.9 The TicketTag.jsp File
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">  <html>  <head>  <%@ taglib uri="jppticket-taglib.tld" prefix="jpp" %>  <title>Parameter Passing</title>  </head>  <body>  <h1>Parameter passing</h1>  <br>  <b>  <jpp:ticketTag param1="13" />  <b>  </body>  </html> 

The only type of parameter we can pass here is a literal because this taglib doesn't contain the proper instructions to allow a dynamic attribute value.

If we change the taglib, we can then take this parameter from a form. If we can take a parameter from a form, we can use a taglib to do a database access. Listing 24.10 shows a form that calls a JSP that accepts a dynamic value.

Listing 24.10 The RetrieveTicketTagForm.html File
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  <HTML>    <HEAD>      <TITLE>Retrieve a Ticket</TITLE>    </HEAD>    <H1 align="CENTER">    Enter the customer ID    </H1>    <FORM action='/examples/jsp/jpp/TicketTag2.jsp'>       Customer ID:         <INPUT TYPE="TEXT" NAME="custID"><BR><BR>       <CENTER>          <INPUT TYPE="SUBMIT">       </CENTER>    </FORM>    </BODY>  </HTML> 

This form's action calls the TicketTag2.jsp file.

 <FORM action='/examples/jsp/jpp/TicketTag2.jsp'> 

Listing 24.11 shows this JSP file.

Listing 24.11 The TicketTag2.jsp File
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">  <html>  <head>  <%@ taglib uri="jppticket-taglib2.tld" prefix="jpp" %>  <title>Ticket Selection</title>  </head>  <body>  <h1>Ticket Selected</h1>  <br>  <b>  <%     String custIDString =  request.getParameter("custID");  %>   <jpp:ticketTag custID= '<%= custIDString %>' />  <b>  </body>  </html> 

Notice that the custID is now extracted from the request object.

 String custIDString =  request.getParameter("custID"); 

This custIDString is used as the parameter passed to the implementing class file.

 <jpp:ticketTag custID= '<%= custIDString %>' /> 

The taglib must also be changed to accept dynamic attributes. Listing 24.12 shows this new taglib.

Listing 24.12 The jppticket-taglib2.tld File
 <?xml version="1.0" encoding="UTF-8" ?>   <!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>  <!-- after this the default space is          "http://java.sun.com/j2ee/dtds/jsptaglibrary_1_2.dtd"     -->  <tlibversion>1.0</tlibversion>  <jspversion>1.1</jspversion>  <shortname>jpptaglib</shortname>  <info>     A tag library from Java Primer Plus  </info>  <tag>  <name>ticketTag</name>  <tagclass>com.samspublishing.jpp.ch25.TicketTag2</tagclass>  <bodycontent>empty</bodycontent>  <info>a Hello World custom tag example</info>  <attribute>     <name>custID</name>     <required>true</required>     <rtexprvalue>true</rtexprvalue>  </attribute>  </tag>  </taglib> 

The custID attribute must be told explicitly that a dynamic parameter can be used. The <rtexprvalue> tag stands for runtime expression value. Setting it to true tells the JSP engine that runtime expressions are allowed. By default, this value is false.

Listing 24.13 shows the class file associated with this example.

Listing 24.13 The TicketTag2.java File
 /*   * TicketTag2.java   *   * Created on July 13, 2002, 12:38 PM   */  package com.samspublishing.jpp.ch25;  import javax.servlet.jsp.*;  import javax.servlet.jsp.tagext.*;  import java.io.*;  import java.sql.*;  import java.util.*;  /**   *   * @author  Stephen Potts   * @version   */  public class TicketTag2 extends TagSupport  {     private String custIDString;     //information about the customer     private int custID;     private String lastName;     private String firstName;     //information about the cruise     private int cruiseID;     private String destination;     private String port;     private String sailing;     private int numberOfTickets;     public int doStartTag()     {        retrieveFromDB();        /*lastName = "Joe";        firstName = "Burns";        //information about the cruise        cruiseID = 1001;         destination = "Cuba";        port = "Tampa";        sailing = "1/1/03";        numberOfTickets = 4;         **/        try        {           JspWriter out = pageContext.getOut();           out.print("The custID that you entered = " + custID);           out.print("<br>" );           out.print("The Last Name = " + lastName);           out.print("<br>" );           out.print("The First Name = " + firstName);           out.print("<br>" );           out.print("The cruiseID = " + cruiseID);           out.print("<br>" );           out.print("The destination = " + destination);           out.print("<br>" );           out.print("The port = " + port);           out.print("<br>" );           out.print("The sailing = " + sailing);           out.print("<br>" );           out.print("The number of tickets = " + numberOfTickets);        }catch (Exception e)        {           System.out.println("Error in TicketTag2 class" + e);        }        return(SKIP_BODY);     }     public void setCustID(String id)      {        this.custIDString=id;        this.custID = Integer.parseInt(custIDString);     }     public String retrieveFromDB()     {        java.sql.Connection dbConn = null;        Statement statement1 = null;        String createStatement;        String insertStatement;        try        {           // ============== Make connection to database ==================           //load the driver class           Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");           //Specify the ODBC data source           String sourceURL = "jdbc:odbc:TicketRequest";            //get a connection to the database           dbConn = DriverManager.getConnection(sourceURL);           //If we get to here, no exception was thrown           System.out.println("The database connection is " + dbConn);           System.out.println("Making connection...\n");           //Create the statement           statement1 = dbConn.createStatement();           //Populate the bean           String getBeanString =           "SELECT * FROM TicketRequest " +           "WHERE CustID = " + custID;           ResultSet results = statement1.executeQuery(getBeanString);           while (results.next())           {              lastName = results.getString("lastName");              firstName = results.getString("firstName");              cruiseID = results.getInt("cruiseID");              destination = results.getString("destination");              port = results.getString("port");              sailing = results.getString("sailing");              numberOfTickets = results.getInt("numberOfTickets");           }           return "Successful Retrieval";        } catch (Exception e)        {           System.out.println("Exception was thrown: " + e.getMessage());           return "UnSuccessful Retrieval";        } finally        {           try           {              if (statement1 != null)                 statement1.close();              if (dbConn != null)                 dbConn.close();           } catch (SQLException sqle)           {              System.out.println("SQLException during close(): " +                                                sqle.getMessage());           }        }     }  } 

The support for the parameter passing is provided by the addition of the setCustID() method.

 public void setCustID(String id)  {     this.custIDString=id;     this.custID = Integer.parseInt(custIDString);  } 

Accessing the database is done using JDBC in the retrieveFromDB() method.

 public String retrieveFromDB()  { 

We connect to the database in typical JDBC fashion. See Chapter 19, "Accessing Databases with Java Database Connectivity (JDBC)," for a detailed explanation of JDBC connection code.

 //load the driver class  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  //Specify the ODBC data source  String sourceURL = "jdbc:odbc:TicketRequest";  //get a connection to the database  dbConn = DriverManager.getConnection(sourceURL);  //If we get to here, no exception was thrown  System.out.println("The database connection is " + dbConn);  System.out.println("Making connection...\n");  //Create the statement  statement1 = dbConn.createStatement(); 

We create the SQL string.

 //Populate the class  String getBeanString =  "SELECT * FROM TicketRequest " +  "WHERE CustID = " + custID; 

Next, we execute the query and obtain the ResultSet. The ResultSet object contains all of the information that was returned by the execution of the query.

 ResultSet results = statement1.executeQuery(getBeanString); 

We extract the parameters from the ResultSet object by making a series of get calls. Each get call is tailored to the data type of the data in the database. In this way, we move data from the database into class-level variables that can be manipulated or displayed.

 while (results.next())  {     lastName = results.getString("lastName");     firstName = results.getString("firstName");     cruiseID = results.getInt("cruiseID");     destination = results.getString("destination");     port = results.getString("port");     sailing = results.getString("sailing");     numberOfTickets = results.getInt("numberOfTickets");  } 

The final step is to return these values to the JSP using the JspWriter object. The out.print() method is the easiest way to send information to the JSP for display.

 JspWriter out = pageContext.getOut();  out.print("The custID that you entered = " + custID);  out.print("<br>" );  out.print("The Last Name = " + lastName);  out.print("<br>" );  out.print("The First Name = " + firstName);  out.print("<br>" );  out.print("The cruiseID = " + cruiseID);  out.print("<br>" );  out.print("The destination = " + destination);  out.print("<br>" );  out.print("The port = " + port);  out.print("<br>" );  out.print("The sailing = " + sailing);  out.print("<br>" );  out.print("The number of tickets = " + numberOfTickets); 

To run this program, type the following line in the address bar on your browser and enter a value:

 http://localhost:1776/examples/RetrieveTicketTagForm.html 

The result of running this program is shown in Figure 24.4.

Figure 24.4. A tag can be used to retrieve data from a database.

graphics/24fig04.gif

All the data extracted from the database is displayed in the browser.


       
    Top
     



    Java 2 Primer Plus
    Java 2 Primer Plus
    ISBN: 0672324156
    EAN: 2147483647
    Year: 2001
    Pages: 332

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net