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.3. Creating a JavaBean as a Web Page Parser

Problem

You want to create a JavaBean that web components can use to parse an HTML page.

Solution

Use the Java API classes for parsing HTML from the javax.swing.text subpackages. Store the JavaBean in WEB-INF/classes or in a JAR placed inside WEB-INF/lib.

Discussion

Example 26-4 is a JavaBean whose sole purpose is to parse a web page for live stock quotes. A servlet or JSP can use this JavaBean for its special purpose, and thus avoid the clutter of taking on the parsing responsibility itself. All of the code, including the inner class representing a ParserCallback, is reproduced from this chapter's earlier recipes. What's new is the setter or mutator method for the bean's stock symbol: setSymbol(String symbol).

Example 26-4. A JavaBean for use with servlets and JSPs

package com.jspservletcookbook;  

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.MalformedURLException;import javax.swing.text.html.HTMLEditorKit.ParserCallback;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.parser.ParserDelegator; public class StockPriceBean { private static final String urlBase = "http://finance.yahoo.com/"+ "q?d=t&s="; private BufferedReader webPageStream = null; private URL stockSite = null; private ParserDelegator htmlParser = null; private MyParserCallback callback = null; private String htmlText = ""; private String symbol = ""; private float ...

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