Skip to Main Content
Java Servlet Programming
book

Java Servlet Programming

by Jason Hunter
November 1998
Intermediate to advanced content levelIntermediate to advanced
526 pages
14h 38m
English
O'Reilly Media, Inc.
Content preview from Java Servlet Programming

Page Generation

The most basic type of HTTP servlet generates a full HTML page. Such a servlet has access to the same information usually sent to a CGI script, plus a bit more. A servlet that generates an HTML page can be used for all the tasks where CGI is used currently, such as for processing HTML forms, producing reports from a database, taking orders, checking identities, and so forth.

Writing Hello World

Example 2.1 shows an HTTP servlet that generates a complete HTML page. To keep things as simple as possible, this servlet just says " Hello World” every time it is accessed via a web browser.[3]

Example 2-1. A servlet that prints “Hello World”

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {

  public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    out.println("<HTML>");
    out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>");
    out.println("<BODY>");
    out.println("<BIG>Hello World</BIG>");
    out.println("</BODY></HTML>");
  }
}

This servlet extends the HttpServlet class and overrides the doGet() method inherited from it. Each time the web server receives a GET request for this servlet, the server invokes this doGet() method, passing it an HttpServletRequest object and an HttpServletResponse object.

The HttpServletRequest represents the client’s request. This object gives a servlet access to information ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java Servlet Programming, 2nd Edition

Java Servlet Programming, 2nd Edition

Jason Hunter, William Crawford

Publisher Resources

ISBN: 156592391XSupplemental ContentCatalog PageErrata