18.7 A Tool Application

Java Servlet Programming, 2nd Edition > 18. JavaServer Pages > 18.7 A Tool Application

 
< BACKCONTINUE >

18.7 A Tool Application

Now that we have the ability to execute includes and embed JavaBeans into our JSP pages, let's look at how we might use these features to write the tool view application. We'll embed a bean into the JSP page that gives the page access to the tool information and let the page act as the view onto that data. Example 18-8 shows the JSP page, called toolview.jsp.

Example 18-8. A Tool View Application Using JSP
<%-- toolview.jsp --%> <%   String title = "Tool Listing";   String deck = "A list of content creation tools";   String desc = "Without tools, people are nothing more than animals.  And " +                 "pretty weak ones at that.  Here's a list of servlet-based " +                 "content creation tools you can use so you won't be a " +                 "servlet weakling."; %> <%@ include file="/header.jsp" %> <%@ page session="false" %> <%@ page errorPage="/errorTaker.jsp" %> <jsp:useBean   scope="application">   <jsp:setProperty name="toolbean" property="toolsFile"                 value='<%= application.getInitParameter("toolsFile") %>' /> </jsp:useBean> <%   Tool[] tools = toolbean.getTools(request.getParameter("state"));   for (int i = 0; i < tools.length; i++) {     Tool tool = tools[i]; %>   <HR SIZE=2 ALIGN=LEFT>   <H3>   <%= tool.name %>   <% if (tool.isNewWithin(45)) { %>     <FONT COLOR=#FF0000><B> (New!) </B></FONT>   <% } else if (tool.isUpdatedWithin(45)) { %>     <FONT COLOR=#FF0000><B> (Updated!) </B></FONT>   <% } %>   </H3>   <A HREF="<%= tool.homeURL %>"><%= tool.homeURL %></A><BR>   <%= tool.comments %> <% } %> <%@ include file="/footer.jsp" %>

First we define the title, deck, and description of the page as Strings within a scriptlet. We then use the include directive to include standard header content from header.jsp and standard footer content (at the end of the file) from footer.jsp. The include directive places the content of the header and footer files into this file during the translation phase, so the title, deck, and desc variables are visible from within the included files, and in fact header.jsp does make use of these variables. The header.jsp and footer.jsp files are shown in Example 18-9 and Example 18-10.

Example 18-9. The header.jsp File
<%-- header.jsp --%> <%-- Depends on variables title, deck, and desc being present --%> <HTML><HEAD><TITLE><%= title %></TITLE></HEAD> <BODY BGCOLOR="#FFFFFF" BACKGROUND="/images/background.gif"       LINK="#003333" ALINK="#669999" VLINK="#333333"> <IMG src="/books/1/318/1/html/2//images/banner.gif" WIDTH=600 HEIGHT=87 BORDER=0><BR> <TABLE> <TR> <TD WIDTH=125 ROWS=10 VALIGN=TOP>  <BR><BR><BR>  <FONT FACE="Arial,Helvetica" SIZE="+1" COLOR="#FF0000">  <A HREF="/index.html">Home</A><BR>  <A HREF="/hosting.html">Hosting</A><BR>  <A HREF="/engines.html">Engines</A><BR>  </FONT> </TD> <TD WIDTH=475>   <TABLE CELLPADDING=5><TR><TD WIDTH=600 BGCOLOR="#006699" VALIGN=TOP>   <B><FONT FACE="Arial,Helvetica" SIZE="+2">   <%= title %>   </FONT></B>   </TD></TR></TABLE>   <B><FONT FACE="Arial,Helvetica" SIZE="+1" COLOR="#003366">   <%= deck %>   </FONT></B><P>   <P>   <FONT FACE="Arial,Helvetica">   <%= desc %>
Example 18-10. The footer.jsp File
<%-- footer.jsp --%> <%-- Has no dependencies on any variables being present --%>  </FONT> </TD> </TR> <TR> <TD></TD> <TD WIDTH=475 ALIGN=CENTER COLSPAN=3> <HR> <FONT FACE="Arial,Helvetica"> <A HREF="/index.html">Home</A>&nbsp;&nbsp; <A HREF="/hosting.html">Hosting</A>&nbsp;&nbsp; <A HREF="/engines.html">Engines</A>&nbsp;&nbsp;<P> </FONT> <TABLE WIDTH=100%> <TR> <TD WIDTH=260 ALIGN=LEFT VALIGN=TOP> <FONT FACE="Arial,Helvetica"> <A HREF="/copyright.html">Copyright</A> &copy; 2000 Jason Hunter<BR> All Rights Reserved.</TD> <TD WIDTH=5></FONT></TD> <TD WIDTH=230 ALIGN=RIGHT VALIGN=TOP> <FONT FACE="Arial,Helvetica"> Contact: <A HREF="mailto:webmaster@servlets.com">webmaster@servlets.com</a> </FONT></TD> </TR> </TABLE> </TD> </TR> </TABLE> </BODY> </HTML>

Next in the toolview.jsp page we use the <jsp:useBean> action to embed a JavaBean named toolbean that's an instance of the class ToolBean. The bean is scoped to application so a single instance of the data will be automatically stored in the context and made available to all pages.

Within the body of the <jsp:useBean> tag we place a <jsp:setProperty> action that sets the toolsFile property on the bean to the value of the context init parameter toolsFile, using a request-time attribute expression to extract the value. This tells the bean the file from which it can load the tool information. It would be ideal if the bean could access the application variable directly to retrieve this information, but beans have access only to what the JSP page provides. It would be elegant if perhaps the bean could accept the filename as a parameter to its constructor, but beans are instantiated using the default no-argument constructor, so this isn't possible either. The approach we take is to include the <jsp:setProperty> action within the body of the <jsp:useBean> tag so the first time the bean is constructed, it's directly given the filename to load from.

Two things to notice about the request-time attribute expression. First, we had to use single quotes around the value because we used double quotes inside the expression. This keeps the JSP parser from becoming confused. We could also have escaped the double quotes within the expression using backslashes. Second, if the init parameter does not exist and the getInitParameter( ) call returns null, that causes a JspException to be thrown, because a null value is not legal in a request-time attribute expression.[4]

[4] Technically the JSP specification makes no comment on what should happen with a null request-time attribute expression. The Tomcat reference implementation therefore becomes the arbitrator, and Tomcat 3.2 throws an exception.

After the <jsp:useBean> tag we use a scriptlet to extract the array of tools from the bean, calling the getTools( ) method with the value of the state parameter in case the user wants to view only tools with a certain state. It's tempting to want to write a <jsp:setProperty> action that would let the bean access the state parameter value directly, but because we gave the bean application scope we cannot to do so would cause concurrency issues as multiple requests tried to set the same property on the bean's single shared instance.

Once we retrieve the array of tools, we use a little more scriptlet code to start a for loop iterating over the array. Inside the for loop we place the logic that displays each individual tool. We use expressions to print simple values like the tool's name, URL, and comments. We use scriptlets to handle the printing of the New or Updated status remark.[5]

[5] Because of JSP whitespace-preservation rules you must be careful when writing if/else statements with scriptlets. The following code would not work:

<% if (tool.isNewWithin(45)) { %>   <FONT COLOR=#FF0000><B> (New!) </B></FONT> <% } %> <% else if (tool.isUpdatedWithin(45)) { %>   <FONT COLOR=#FF0000><B> (Updated!) </B></FONT> <% } %>
With this code, the background servlet would attempt to print a new line between the if and else clauses, causing the obscure compile error: 'else' without 'if'.

The code for the ToolBean class is in Example 18-11. The code for the Tool class is the same as shown in Chapter 14.

Example 18-11. The Supporting ToolBean Class
import java.util.*; public class ToolBean {   private Tool[] tools;   private String state;   public ToolBean() { }   public void setToolsFile(String toolsFile) throws Exception {     // No way to gain access to the application context directly from a bean     tools = Tool.loadTools(toolsFile);   }   public Tool[] getTools(String state) throws Exception {     if (tools == null) {       throw new IllegalStateException(         "You must always set the toolsFile property on a ToolBean");     }     if (state == null) {       return tools;     }     else {       // Return only tools matching the given "state"       List list = new LinkedList();       for (int i = 0; i < tools.length; i++) {         if (tools[i].getStateFlag().equalsIgnoreCase(state)) {           list.add(tools[i]);         }       }       return (Tool[]) list.toArray(new Tool[0]);     }   } }

The setToolsFile( ) method is called automatically by the <jsp:setProperty> action right after the bean is constructed. It loads the tool information from the specified file.

The getTools( ) method is called by the JSP page directly from within a scriptlet. The method accepts as a parameter the state of the tools to match against; if the state is null it returns the full list. If the tools variable is null, then setToolsFile( ) must not have completed successfully, and the bean throws an IllegalStateException warning the user of the problem.


Last updated on 3/20/2003
Java Servlet Programming, 2nd Edition, © 2001 O'Reilly

< BACKCONTINUE >


Java servlet programming
Java Servlet Programming (Java Series)
ISBN: 0596000405
EAN: 2147483647
Year: 2000
Pages: 223

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