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.4. Using the Web Page Parsing JavaBean in a Servlet

Problem

You want to use the JavaBean for parsing HTML in a servlet.

Solution

Create an instance of the bean in the appropriate service method (e.g., doGet( ) or doPost( )) and call its methods.

Discussion

The JavaBean has to be available to the servlet, and therefore stored in WEB-INF/classes, including subdirectories that match the bean's package name. The JavaBean can also be stored in a JAR inside of WEB-INF/lib.

Since the JavaBean in Example 26-5 shares the servlet's package (com.jspservletcookbook), the servlet class does not have to import the bean class.

Note

If the JavaBean resides in a different package in the web application, then the servlet has to include an import statement such as the following example:

import com.parkerriver.beans.BeanParserServlet;

The doGet( ) method provides an HTML form for entering a stock symbol (such as "intc"). The doPost( ) method then creates an instance of the StockPriceBean, calls the bean's setSymbol( ) method, and finally displays the stock price by calling the bean's getLatestPrice( ) method.

Example 26-5. A servlet uses a specially designed JavaBean to get a live stock quote

package com.jspservletcookbook;    

import java.io.IOException;  
import java.io.PrintWriter;     

import javax.servlet.*;
import javax.servlet.http.*;public class BeanParserServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { //set ...

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