Sample Program: Writing Your Custom Tag Library

See if you can build a custom tag library and modify the book shopping cart application implemented in the JSP. You will be writing a custom tag library to support displaying the price of the books using the <ctt:MoneyFormat/> tag. This tag has an attribute MoneyValue, the value of which is the price of the book. Your custom tag will convert this book price into a formatted price and put it in the JSP. Apart from this, you will also use WebLogic's custom tag library and use the <wl:cache></wl:cache> tags to display the shopping cart information. These custom tags will be used in the ShoppingCartJsp.jsp and ViewCartJsp.jsp files.

For writing the custom tag handler, the first step is to write the TLD file. Writing this file first gives you an overview of what you are going to develop, what the structure of the tag will be, and so on. See Listing 6.1.

Listing 6.1 customTagsTLD.tld Tag Library Descriptor File
 <?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>   <tlibversion>1.0</tlibversion>   <jspversion>1.1</jspversion>   <shortname>ctt</shortname>   <info>     This tag library calls the rounding functions and the money format             functions available in utility classes   </info>   <tag>     <name>MoneyFormat</name>     <tagclass>com.sams.learnweblogic7.tagLibClasses.MoneyFormat</tagclass>     <bodycontent>empty</bodycontent>   </tag> </taglib> 

As was studied earlier, the TLD file contains the custom tag information enclosed in the <taglib></taglib> tags. The custom tag MoneyFormat is defined here by specifying this name for the tag in the <name></name> tags under the <tag></tag> tags in the file. Because your custom tag will not have any body, you will be specifying the value empty for the <bodycontent></bodycontent> tags of the MoneyFormat custom tag. It is not mandatory to specify the <bodycontent> tag. The tag handler class that will be invoked to process the MoneyFormat custom tag is the com.sams.learnweblogic7.tagLibClasses.MoneyFormat class specified between the <tagclass></tagclass> tags.

The next step is to build the actual tag handler class MoneyFormat.java. The code for this tag handler class is found in Listing 6.2.

Listing 6.2 MoneyFormat.java Custom Tag Handler
 /******************************************************************************   * Class Name   :MoneyFormat.java   * Description  :Tag handler class for formatting the billing amounts in the   *               Book Shopping Cart Application   * @author Mandar S. Chitnis, Lakshmi AM.       @version 1.1   * Copyright (c) by Sams Publishing. All Rights Reserved. *******************************************************************************/ package com.sams.learnweblogic7.tagLibClasses; import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import com.sams.learnweblogic7.utils.*; /**  * This class displays the amount in the requested format, or $ as default.  */ public class MoneyFormat extends TagSupport{   private double moneyValue;   public int doStartTag() {     System.out.println("Inside the tag in dostart");     try{         JspWriter out = pageContext.getOut();         moneyValue = getMoneyValue();         out.println(Utility.getMoneyFormat(moneyValue));       }     catch(Exception e){         System.out.println("Please check your code");         e.printStackTrace();     }     finally{         return(SKIP_BODY);     }   }   public void setMoneyValue(double moneyVal){     this.moneyValue = moneyVal;   }   public double getMoneyValue(){     return moneyValue;   } } 

You will initially be importing the necessary packages for the classes that you will use in the development of the custom tag handler:

 import java.io.*;  import java.util.*; import javax.servlet.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import com.sams.learnweblogic7.utils.*; /**  * This class displays the amount in the requested format, or $ as default.  */ public class MoneyFormat extends TagSupport{ ... 

The MoneyFormat.java is a custom tag handler class for a custom tag without a body. Hence, you will be extending the MoneyFormat.java class from the TagSupport class which is imported from the javax.servlet.jsp.tagext.* package.

The MoneyFormat class contains a variable moneyValue of type double. This is used to handle the attribute MoneyValue passed along with the custom tag. To handle the MoneyValue attribute, you will write a get/set method combination:

 public void setMoneyValue(double moneyVal){     this.moneyValue = moneyVal;   }   public double getMoneyValue(){     return moneyValue;   } 

Finally, to get the custom tag implementation in place, you will override the doStartTag() method of the TagSupport class:

 public int doStartTag() {     System.out.println("Inside the tag in dostart");     try{         JspWriter out = pageContext.getOut();         moneyValue = getMoneyValue();         out.println(Utility.getMoneyFormat(moneyValue));       }     catch(Exception e){         System.out.println("Please check your code");         e.printStackTrace();     }     finally{         return(SKIP_BODY);     }   } 

The doStartTag() method gets the reference to the output stream of the JSP (the JspWriter) by calling the getOut() method of the pageContext object (initialized by the TagSupport base class.) The value of the attribute MoneyValue set in the custom tag within the JSP is accessed by the custom tag handler using the getMoneyValue() accessor method. The retrieved book price is then formatted using the Utility helper class and printed to the JSP output stream using the JspWriter object. Because your custom tag does not contain body contents, you will be returning from the doStartTag() method with the SKIP_BODY constant.

Now you need to include the custom tag in the JSP file. Listing 6.3 shows the code for the ShoppingCartJsp.jsp and the ViewCartJsp.jsp files.

Listing 6.3 ShoppingCartJsp.jsp
 /******************************************************************************   * Class Name   :ShoppingCartJsp.jsp   * Description  :Demonstrates the use of WebLogic custom tags.   * @author Mandar S. Chitnis, Lakshmi AM.       @version 1.1   * Copyright (c) by Sams Publishing. All Rights Reserved. *******************************************************************************/ <%@ taglib uri="weblogic-tags.tld" prefix="wl" %> <%@ taglib uri="customTagsTLD.tld" prefix="ctt" %> <%@ page import="com.sams.learnweblogic7.utils.*, com.sams.learnweblogic7.servlets.*, com.sams.learnweblogic7.tagLibClasses.*, java.util.*" %> <%! Book book1; %> <%! Book book2; %> <%! Book book3; %> <%! ServletContext sc; %> <%! Hashtable shoppingCartHash = null; %> <%! HttpSession session; %> <%! private static final int DEFAULT_ZERO_VALUE = 0; %> <%         sc = getServletConfig().getServletContext();         String clickedButton =                 (request.getParameter("buttonName") == null)?"":                 request.getParameter("buttonName");         if(clickedButton.equals("Empty Shopping Cart"))         weblogic.servlet.security.ServletAuthentication.invalidateAll(request);         session = request.getSession(true);         if(session.isNew()){             //getting the init params             String book1Id = config.getInitParameter("book1Id");             String book1Name = config.getInitParameter("book1Name");             double book1Price =                     new Double(config.getInitParameter("book1Price")).doubleValue();             String book1Image = config.getInitParameter("book1Image");             String book1Description =                     config.getInitParameter("book1Description");             book1 =                     new Book(book1Id, book1Name, book1Price, book1Image,                     book1Description);             sc.setAttribute("book1",book1);             String book2Id = config.getInitParameter("book2Id");             String book2Name = config.getInitParameter("book2Name");             double book2Price =                     new Double(config.getInitParameter("book2Price")).                     doubleValue();             String book2Image = config.getInitParameter("book2Image");             String book2Description =                     config.getInitParameter("book2Description");             book2 =                     new Book(book2Id, book2Name, book2Price, book2Image,                     book2Description);             sc.setAttribute("book2", book2);             String book3Id = config.getInitParameter("book3Id");             String book3Name = config.getInitParameter("book3Name");             double book3Price =                     new Double(config.getInitParameter("book3Price")).                     doubleValue();             String book3Image = config.getInitParameter("book3Image");             String book3Description =                     config.getInitParameter("book3Description");             book3 =                     new Book(book3Id, book3Name, book3Price, book3Image,                     book3Description);             sc.setAttribute("book3", book3);             //create an empty shopping cart hashtable, with zero quantity             //for each book id             shoppingCartHash = new Hashtable();             shoppingCartHash.put(book1.getBookId(),                     new Integer(DEFAULT_ZERO_VALUE));             shoppingCartHash.put(book2.getBookId(),                     new Integer(DEFAULT_ZERO_VALUE));             shoppingCartHash.put(book3.getBookId(),                     new Integer(DEFAULT_ZERO_VALUE));             session.setAttribute("shoppingCartHash", shoppingCartHash);         }         else         {             book1 = (Book)sc.getAttribute("book1");             book2 = (Book)sc.getAttribute("book2");             book3 = (Book)sc.getAttribute("book3");             if(clickedButton.equals("view"))             {                     RequestDispatcher rd =  sc.getRequestDispatcher("/ViewCartJsp");                     //here, if you use include, it will show the view cart page                     // and the page following this scriplet tag                     rd.forward(request,response);             }             else if(clickedButton.equals("add"))             {                 shoppingCartHash=(session.getAttribute("shoppingCartHash") ==                         null)?new Hashtable():(Hashtable)session.getAttribute                         ("shoppingCartHash");                 int Book1Qty = Utility.getDefaultValue(((Integer)shoppingCartHash.get(book1.getBookId         ())).toString(),DEFAULT_ZERO_VALUE)+         Utility.getDefaultValue(request.getParameter("book1_qty"),         DEFAULT_ZERO_VALUE);                 int Book2Qty = Utility.getDefaultValue(((Integer)shoppingCartHash.get(book2.getBookId         ())).toString(),DEFAULT_ZERO_VALUE)+         Utility.getDefaultValue(request.getParameter("book2_qty"),         DEFAULT_ZERO_VALUE);                 int Book3Qty = Utility.getDefaultValue(((Integer)shoppingCartHash.get(book3.getBookId         ())).toString(),DEFAULT_ZERO_VALUE)+         Utility.getDefaultValue(request.getParameter("book3_qty"),         DEFAULT_ZERO_VALUE);                 shoppingCartHash.put(book1.getBookId(), new Integer(Book1Qty));                 shoppingCartHash.put(book2.getBookId(), new Integer(Book2Qty));                 shoppingCartHash.put(book3.getBookId(), new Integer(Book3Qty));                 session.setAttribute("shoppingCartHash", shoppingCartHash);             }         } %> <wl:cache name="commonHeader" scope="session"> <HTML> <HEAD>     <TITLE>         Shopping Cart Example using JSP's and HTTP session     </TITLE> </HEAD> <BODY> <FORM name="addcart" action="/ShoppingApp/ShoppingCartJsp" method="post"> <B><FONT face="Verdana" color="blue" size=-2><P align="right">Shopping Cart         using JSP's and Http Session</P></FONT></B> </wl:cache> <CENTER><B>Most popular books from Sams Publishing</B></CENTER><BR> <TABLE width = 100%> <TR>   <TH>&nbsp;</TH>   <TH>Book Name and Description</TH>   <TH>Book Price</TH>   <TH>No of Books to add to cart</TH> </TR> <wl:cache name="book1Vars" scope="session"> <TR bgcolor='#cccc99'>   <TD><IMG src="/books/2/96/1/html/2/<%=book1.getImagePath()%>"></TD>   <TD align='left'><B><%=book1.getBookName()%></B><BR>           <%=book1.getBookDescription()%></TD>   <TD align='center'><ctt:MoneyFormat MoneyValue="<%=book1.getBookPrice()%>"/>   </TD> </wl:cache>   <TD align='center'><INPUT type='text' name='book1_qty' size=3></TD> </TR> <wl:cache name="book2Vars" scope="session"> <TR bgcolor='#eeeeee'>   <TD>< IMG src="/books/2/96/1/html/2/<%= book2.getImagePath()%>"></TD>   <TD align='left'><B><%=book2.getBookName()%></B><BR>           <%=book2.getBookDescription()%></TD>   <TD align='center'><ctt:MoneyFormat MoneyValue="<%=book2.getBookPrice()%>"/>   </TD> </wl:cache>   <TD align='center'><INPUT type='text' name='book2_qty' size=3></TD> </TR> <wl:cache name="book3Vars" scope="session"> <TR bgcolor='#cccc99'>   <TD>< IMG src="/books/2/96/1/html/2/<%= book3.getImagePath()%>"></TD>   <TD align='left'><b><%=book3.getBookName()%></b><BR>           <%=book3.getBookDescription()%></TD>   <TD align='center'><ctt:MoneyFormat MoneyValue="<%=book3.getBookPrice()%>"/>   </TD> </wl:cache>   <TD align='center'><INPUT type='text' name='book3_qty' size=3></TD> </TR> </TABLE> <BR> <CENTER><TABLE width=100%> <TR>   <TD><INPUT type="submit" name="buttonName" value="add"></TD>   <TD><INPUT type="submit" name="buttonName" value="view"></TD> </TR> </TABLE></CENTER> <wl:cache name="commonFooter" scope="session"> </FONT> </FORM> </BODY> </HTML> </wl:cache> 

From the preceding code for the ShoppingCartJsp.jsp, take a look at the first statement, where you use the custom tag library that you developed and WebLogic's custom tag library in the JSP:

 <%@ taglib uri="weblogic-tags.tld" prefix="wl" %>  <%@ taglib uri="customTagsTLD.tld" prefix="ctt" %> 

You will be using the <wl:cache> tag in order to cache the book-listing data in this JSP. A code snippet showing its use is given here:

 <wl:cache name="book1Vars" scope="session">  <TR bgcolor='#cccc99'>    <TD><img src="/books/2/96/1/html/2/<%= book1.getImagePath()%>"></TD>    <TD align='left'><b><%=book1.getBookName()%></b><BR>            <%= book1.getBookDescription()%></TD>    <TD align='center'><ctt:MoneyFormat MoneyValue="<%=book1.getBookPrice()%>"/>    </TD> </wl:cache> <TD align='center'><INPUT type = 'text' name='book1_qty' size = 3></TD></TR> 

The <wl:cache> tag caches the book information for the entire book1 object to be retrieved at any time in the JSP. In addition to this, you are using your custom tag handler <ctt:MoneyFormat MoneyValue=<%=book1.getBookPrice()%>. Your custom tag has an attribute MoneyValue to which is set the price of the book1 object. This is passed to your tag handler, which formats the price and writes it to the JSP output stream.

Because the ViewCartJsp.jsp has similar code for the two custom tag handlers, it will not be listed here for the sake of brevity.

The custom tag handler is in place! Go to the next step compiling the custom tag handler.

Compile the Program

Use the compile.bat provided to compile the servlet. The batch file compiles the MoneyFormat.java file located in the

 applications\ShoppingApp\WEB-INF\classes\com\sams\learnweblogic7\tagLibClasses\  

directory in your domain.

To verify that the compilation is successful, the corresponding .class files for the MoneyFormat.java will be created in the directory

 c:\bea\user_domains\mydomain\applications\ShoppingApp\WEB-INF\classes\          com\sams\learnweblogic7\tagLibClasses 

Deploy the Program

After a successful compilation, the custom tag handler class needs to be deployed in the WebLogic Server environment. It is optional to package the custom tag handler in a .jar file. Use the exploded form of the MoneyFormat class in the sample program.

Registering Your Custom Tag Handler in web.xml

Once your custom tag handler class is ready, you need to register it with WebLogic Server before it can be used in any JSP. The following statements need to be added to the deployment descriptor file web.xml:

 <taglib>      <taglib-uri>customTagsTLD.tld</taglib-uri>     <taglib-location>/WEB-INF/lib/customTagsTLD.tld</taglib-location>     <attribute>          <name>MoneyValue</name>          <required>false</required>          <rtexprvalue>true</rtexprvalue>     </attribute> </taglib> 

From Figure 6.3, you can see the entries for the TLD that you developed the customTagsTLD.tld file registered using the <taglib-uri> tags enclosed within the <taglib></taglib> tags.

Figure 6.3. Registering the custom tag handler in the web.xml file.

graphics/06fig03.jpg

You will be placing the tag handler Java classes in the directory indicated in Figure 6.4.

Figure 6.4. Deployment directory structure for the custom tag handler.

graphics/06fig04.jpg

Execute the Program

The JSP is invoked from the browser by calling the following URL:

http://localhost:7001/ShoppingApp/ShoppingCartJsp.jsp

Your browser should display the file similar to the screen shot in Figure 6.5.

Figure 6.5. Screen shot of the ShoppingCartJsp.jsp.

graphics/06fig05.jpg

Clicking the View Cart button pulls up the ViewCartJsp.jsp page as shown in Figure 6.6.

Figure 6.6. Screen shot of the ViewCartJsp.jsp.

graphics/06fig06.jpg

Notice that there is absolutely no difference in the output generated using the custom tag library. But the cleaner code in the JSP tells a different story altogether!



Sams Teach Yourself BEA WebLogic Server 7. 0 in 21 Days
Sams Teach Yourself BEA WebLogic Server 7.0 in 21 Days
ISBN: 0672324334
EAN: 2147483647
Year: 2002
Pages: 339

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