Java Servlets   «Prev  Next»
Lesson 2 The doGet() servlet method
Objective Describe the parameters of doGet().

doGet Servlet Method

This is the code that you compiled in the previous module for the simplest possible servlet:

import javax.servlet.*;
import javax.servlet.http.*;
public class Simplest extends HttpServlet {

This servlet is useful for testing your setup, but it does not do anything. In order to do something, a servlet must override the doGet() method. That is what the Web server will call when the browser sends a GET request for your servlet. The doGet() method takes two parameters, an empty shell of your override looks like this:

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

Three parts of doGet()

Let us focus on three parts of the doGet() method definition. The first two are parameters, and the third a throws list.
  1. HttpServletRequest req
  2. HttpServletResponse res
  3. throws ServletException, IOException

The first parameter to this method (HttpServletRequest req) is an object representing the request made by the browser. When you were first introduced to the GET that the browser sends to the server you learned that other information, called the request headers, is sent after the GET statement. If you have done server-side programming in CGI or ASP, you have probably used the information in the request headers in that code. Your servlet can look at this information, but not change it. We are not going to use it in your first servlet.
The second parameter (HttpServletResponse res ) is an object representing the response the servlet is building to send back to the browser. You will set properties of this object, or write HTML to it, in all your servlets.
Following the parameter list is the throws clause of the method definition (throws ServletException, IOException). Servlets have their own exceptions, which they may throw. In addition, it’s possible to cause an IOException to be thrown in writing HTML to the response object. This list alerts the server code that calls doGet() to be ready to catch those types of exceptions.
In the next lesson, you will see how to write HTML to the response object.