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

27.4. Using a JSP to Connect with Google

Problem

You want to search Google using the Google Web APIs and a JSP.

Solution

Use the jsp:useBean standard action to get access to the GoogleBean from Example 27-2, then use this bean instance to connect with Google's web tools.

Discussion

The JSP in Example 27-4 uses the JSTL core tags to determine if the user has sent a search query along with their request. If the query request parameter is empty, then the JSP displays a form (see Figure 27-1). See Chapter 23 for details on the JSTL core tags.

If the request parameter is filled by a search query, the JSP uses the GoogleBean to search google.com and display the results. The JSP uses the jsp:useBean standard action to create an instance of the bean, which is stored in the WEB-INF/lib directory.

Example 27-4. A JSP uses a JavaBean to search google.com

<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>

<html>
<head><title>Search Google from a JSP</title></head>
<body>

<c:choose>

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

   <h2>Please enter your search terms...</h2>

   <%-- Display the HTML form... --%> <form method="POST" action ='<c:out value= "${pageContext.request.contextPath}" />/google.jsp'> <table border="0"> <tr><td valign="top"> Search terms: </td> <td valign="top"> <input type="text" name="query" size="15"> </td></tr> <tr><td valign="top"> Restrict to Google sub-site... </td> <td valign="top"> <select name="restrict"> <option selected>none</option><option>unclesam</option> <option>linux</option> ...

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