[ Team LiB ] Previous Section Next Section

Recipe 26.5 Using the Web Page Parsing JavaBean in a JSP


You want to use a JavaBean and JSP to harvest information from a web page.


Use the jsp:useBean standard action to create an instance of the bean.


The same JavaBean that prior recipes created and stored in the web application in WEB-INF/classes can be used by a JSP. The JSP in Example 26-6 uses jsp:useBean to create an instance of the bean named priceFetcher. If the request does not contain a symbol parameter, the JSP displays the HTML form shown in Figure 26-1.

The JSP uses the JSTL core tags to generate this conditional behavior. These tags include c:choose, c:when, and c:otherwise.

If the request to the JSP contains a symbol parameter, the JSP sets the priceFetcher's symbol property to the value of this request parameter. This code is the equivalent of calling the bean's setSymbol( ) method; it passes the name of the stock symbol to the bean so that it can grab a live stock quote from the web page.

Example 26-6. A JSP uses jsp:useBean to employ a web-harvesting JavaBean
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>

<jsp:useBean id="priceFetcher" class=
  "com.jspservletcookbook.StockPriceBean" />

<head><title>Price Fetch</title></head>


  <c:when test="${empty param.symbol}">

    <h2>Please submit a valid stock symbol</h2>

    <form method="POST" action =
     '<c:out value="${pageContext.request.contextPath}" />/priceFetch.jsp'>

    <table border="0"><tr><td valign="top">Stock symbol: </td>  
    <td valign="top">
    <input type="text" name="symbol" size="10"></td></tr>
    <tr><td valign="top">
    <input type="submit" value="Submit Info"></td></tr>



     <h2>Here is the latest value of <c:out value="${param.symbol}" /></h2>

     <jsp:setProperty name="priceFetcher" property="symbol" value=
       "<%= request.getParameter(\"symbol\") %>" />

     <jsp:getProperty name="priceFetcher" property="latestPrice"/>




Now that the JSP has seeded the bean with the stock symbol, this code will call the bean's getLatestPrice( ) method:

<jsp:getProperty name="priceFetcher" property="latestPrice"/>

The JSP's output replaces the jsp:getProperty standard action with the stock price, as long as the stock symbol sent to the bean with jsp:setProperty was valid.

The output of the JSP in Example 26-6 looks just like the output shown in Figures Figure 26-1 and Figure 26-2.

See Also

Chapter 23 on the JSTL; Recipe 26.4 on using a web page parsing JavaBean in a servlet.

    [ Team LiB ] Previous Section Next Section