O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

26.5. Using the Web Page Parsing JavaBean in a JSP

Problem

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

Solution

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

Discussion

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" />

<html>
<head><title>Price Fetch</title></head>
<body>

<c:choose>

  <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> ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required