Here's the outline of a basic servlet that handles GET requests.
GET requests, for those unfamiliar with HTTP, are requests made by browsers when the user:
types in a URL on the address line
follows a link from a Web page
or makes an HTML form that does not specify a METHOD.
Servlets can also very easily handle POST requests, which are generated when someone creates an HTML form that specifies METHOD="POST".
We'll discuss that in later sections.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SomeServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletRequest response)
throws ServletException, IOException {
// Use "request" to read incoming HTTP headers (e.g. cookies)
// and HTML form data (e.g. data the user entered and submitted)// Use "response" to specify the HTTP response line and headers
// (e.g. specifying the content type, setting cookies).
PrintWriter out = response.getWriter();
// Use "out" to send content to browser
}
}
To be a servlet, a class should extend HttpServlet and override doGet or doPost (or both), depending on whether the data is being sent by GET or by POST.
These methods take two arguments:
The HttpServletRequest has methods that let you find out about incoming information such as FORM data, HTTP request headers, and the like.
The HttpServletResponse has methods that:
let you specify the HTTP response line (200, 404, etc.)
let you specify the response headers (Content-Type, Set-Cookie, etc.)
and, most importantly, let you obtain a PrintWriter used to send output back to the client.
For simple servlets, most of the effort is spent in println statements that generate the desired page.
Note that doGet and doPost throw two exceptions, so you are required to include them in the declaration.
Also note that you have to import classes in:
java.io (for PrintWriter, etc.)
javax.servlet (for HttpServlet, etc.)
and javax.servlet.http (for HttpServletRequest and HttpServletResponse).
Finally, note that doGet and doPost are called by the service method, and in a few cases you might want to override service directly.
This tutorial is now available as a book: Core Servlets and JavaServer Pages by Marty Hall, published by Sun Microsystems Press.
Read all about it at CoreServlets.com
JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for
Windows 95, 98, ME, NT, 2000 and XP. It's designed to
automatically optimize your Windows settings, boosting your
Internet connection up to 200%.