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.7. Using a Servlet to Connect with Amazon

Problem

You want to connect with AWS using a servlet.

Solution

Use a specially designed JavaBean to peform the AWS-related tasks.

Discussion

Example 27-6 uses the same design that the Google recipes used, so you should find this servlet code very familiar if you have worked through those examples before. The servlet generates an HTML form in response to a GET HTTP request, which sends the Amazon search terms back to the same servlet. The interesting action takes place in the doPost( ) method, where the servlet uses an AmazonBean class (from Recipe 27.6) to connect with AWS and display any search results.

Example 27-6. A servlet uses a JavaBean to connect with AWS

package com.jspservletcookbook;    

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

import javax.servlet.*;
import javax.servlet.http.*;

public class AmazonServlet extends HttpServlet {
    
  public void doGet(HttpServletRequest request, 
    HttpServletResponse response)
    throws ServletException, java.io.IOException {
    
      //set the MIME type of the response, "text/html"
      response.setContentType("text/html");
    
      java.io.PrintWriter out = response.getWriter( );
    
      //Begin assembling the HTML content
      out.println("<html><head>");
    
      out.println(
      "<title>Initiate an Amazon Book Search</title></head><body>");

      out.println("<h2>Please enter your Amazon search terms</h2>");//Display an HTML form that sends the request back to this
      //'/amazonservlet' which will cause the calling of doPost( ) //make sure method="POST" ...

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