Java Servlets   «Prev  Next»

Lesson 2 The doGet() servlet method
Objective Describe the parameters of doGet().

doGet Servlet Method

Question: What is the purpose of the doGet Servlet Method within the context of the Java Servlet API?
Within the context of the Java Servlet API, the doGet() method plays a crucial role in the processing of HTTP GET requests by a web application. As part of the HttpServlet class, this method is responsible for handling the retrieval of information from the server-side in response to client requests, while ensuring that the application adheres to the principles of the HTTP protocol. The doGet() method is defined in the javax.servlet.http.HttpServlet class, which extends the generic javax.servlet.Servlet class. When a client (typically a web browser) sends an HTTP GET request to a web application, the servlet container selects the appropriate servlet based on the specified URL. Upon identifying the servlet, it invokes the doGet() method, passing along the HttpServletRequest and HttpServletResponse objects, which encapsulate the details of the request and the response, respectively.
The purpose of the doGet() method can be summarized in the following key aspects:
  1. Handle HTTP GET Requests: doGet() is specifically designed to process incoming HTTP GET requests, which are meant for retrieving data from the server without causing any changes to the underlying resources.
  2. Retrieve Information: doGet() retrieves the requested information from the server-side resources, such as databases, files, or other data stores, and prepares it for transmission to the client.
  3. Build Response: Using the HttpServletResponse object, the doGet() method constructs an appropriate HTTP response, which may include setting the content type, setting headers, and writing the response body with the retrieved information.
  4. Maintain Idempotency: In compliance with the HTTP protocol, doGet() ensures that multiple identical requests have the same effect as a single request. This idempotent nature of the GET method guarantees that clients can safely cache, refresh, or retry requests without causing unintended consequences on the server-side.
  5. Support Conditional Requests: doGet() can also accommodate conditional GET requests, which allow clients to request information only if certain conditions are met, such as the resource being modified since the client's last request. This functionality helps minimize bandwidth usage and improve overall performance.

The doGet() servlet method is an integral component of the Java Servlet API, responsible for processing HTTP GET requests, retrieving information from server-side resources, and constructing appropriate HTTP responses. By adhering to the principles of the HTTP protocol and offering support for conditional requests, doGet() plays a pivotal role in ensuring the efficient and robust functioning of Java-based web applications. 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 the doGet() method

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 is 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.

Two Principal HttpServlet Methods

When calling the two principal HttpServlet methods,
  1. doGet( ) or
  2. doPost( ),
the servlet container creates
  1. javax.servlet.http.HttpServletRequest and
  2. HttpServletResponse
objects and passes them in as parameters to these request handler methods. HttpServletRequest represents the request; HttpServletResponse encapsulates the servlet's response to the request.


Example 4-2 shows a typical servlet idiom for handling an HTML form. The doGet( ) method displays the form itself. The doPost( ) method handles the submitted form data, since in doGet( ), the HTML form tag specifies the servlet's own address as the target for the form data.
The servlet (named FirstServlet) specifies that the declared class is part of the com.javadeploy package.
It is important to create packages for your servlets and utility classes, and then to store your classes in a directory structure beneath WEB-INF that matches these package names.
The FirstServlet class imports the necessary classes for compiling a basic servlet, which are the emphasized import statements in Example 4-2. The Java class extends HttpServlet.
The only defined methods are doGet( ) , which displays the HTML form in response to a GET HTTP request, and doPost( ), which handles the posted data.

Java Servlets

Example 4-2: Typical HttpServlet used for handling an HTML form

package com.javadeploy;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FirstServlet 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");
  //use a PrintWriter to send text data to the client who has requested the servlet
  java.io.PrintWriter out = response.getWriter( );
  //Begin assembling the HTML content
  out.println("<html><head>");
  out.println("<title>Help Page</title></head><body>");
  out.println("<h2>Please submit your information</h2>");
  //make sure method="post" so that the servlet service method
  //calls doPost in the response to this form submit


  out.println("<form method=\"post\" action =\"" + request.getContextPath() + 
  "/firstservlet\" >");
  out.println("<table border=\"0\"><tr><td valign=\"top\">");
  out.println("Your first name: </td> <td valign=\"top\">");
  out.println("<input type=\"text\" name=\"firstname\" size=\"20\">");
  out.println("</td></tr><tr><td valign=\"top\">");
  out.println("Your last name: </td> <td valign=\"top\">");
  out.println("<input type=\"text\" name=\"lastname\" size=\"20\">");
  out.println("</td></tr><tr><td valign=\"top\">");
  out.println("Your email: </td> <td valign=\"top\">");
  out.println("<input type=\"text\" name=\"email\" size=\"20\">");
  out.println("</td></tr><tr><td valign=\"top\">");
  out.println("<input type=\"submit\" value=\"Submit Info\"></td></tr>");
  out.println("</table></form>");
  out.println("</body></html>");
 }//doGet

 public void doPost(HttpServletRequest request,
  HttpServletResponse response) throws ServletException, java.io.IOException {
  //display the parameter names and values
  Enumeration paramNames = request.getParameterNames();
  String parName;//this will hold the name of the parameter
  boolean emptyEnum = false;
  if (!paramNames.hasMoreElements())
    emptyEnum = true;
    //set the MIME type of the response,"text/html"
    response.setContentType("text/html");
    //use a PrintWriter to send text data to the client
    java.io.PrintWriter out = response.getWriter();
    //Begin assembling the HTML content
    out.println("<html><head>");
    out.println("<title>Submitted Parameters</title></head><body>");
    if (emptyEnum){
      out.println("<h2>Sorry, the request does not contain any parameters</h2>");
    }else {
      out.println("<h2>Here are the submitted parameter values</h2>");
  }
  while(paramNames.hasMoreElements( )){
    parName = (String) paramNames.nextElement( );
    out.println("<strong>" + parName + "</strong> : " +
    request.getParameter(parName));
    out.println("<br />");
  }//while
 out.println("</body></html>");
 }// doPost
}

In the next lesson, you will see how to write HTML to the response object.
SEMrush Software