doGet and doPost Method in Servlet Example

In this tutorial, we will discuss what is doGet and doPost method in servlet with example. Why we should use doGet and doPost methods in place of the service method.

In the previous HttpServlet tutorial we learned, there are 7 different modes/methods of requests:- GET, POST, PUT, DELETE, OPTIONS, TRACE, and HEAD. The browser software can send only GET and POST mode requests.

We can make servlet components as flexible servlet components having the capability to process both GET and POST mode/method requests either using the service(-,-) method or doGet(-,-) + doPost(-,-) method. In the HttpServlet tutorial, we discussed why writing request processing logic in the service(-,-) method is not a good practice, and why we should use the doGet(-,-) and doPost(-,-) method in our servlet component compared to service(-,-) method.

How to Write logic for the doGet and doPost method in Servlet

There are different ways to process the GET and POST mode request through the doGet and doPost method.

  1. We want to execute the same logic for both GET and POST modes of requests.
  2. We want to execute two different logic for the GET and POST modes of requests.

Different ways to write the logic for doGet(-,-) and doPost(-,-) when we want to execute the same logic for both GET and POST modes of requests.

  • Place request processing logic in a user-defined method and call that method from both doGet(-,-) and doPost(-,-) methods => Not recommended.
  • Override both doGet(-,-) and doPost(-,-) methods and keep request processing logic in one method, call that method from another method => recommended approach.
// ServletComponent.java
/* When we want to execute same logic for both
 * GET and POST mode of request.
 */
public class ServletComponent extends HttpServlet {

   @Override
   public void doPost(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException {

      // request processing logic
   }

   @Override
   public void doGet(HttpServletRequest req, HttpServletResponse resp) 
       throws ServletException, IOException {

     // call doPost in doGet
     doPost(req, resp); 
   }

}

Different ways to write logic for doGet(-,-) and doPost(-,-) when we want to execute different logic for the GET and POST modes of requests.

  • Take two different user-defined methods having GET and POST modes of requests processing logic and call them from doGet(-,-) and doPost(-,-) methods respectively => Not recommended.
  • Override both doGet(-,-) and doPost(-,-) methods having different request processing logics => recommended approach.
// ServletComponent.java 
/* When we want to execute different logic for both
 * GET and POST mode of request.
 */
public class ServletComponent extends HttpServlet {

   @Override
   public void doPost(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException {

      // request processing logic
   }

   @Override
   public void doGet(HttpServletRequest req, HttpServletResponse resp) 
       throws ServletException, IOException {

     // call doPost in doGet
     doPost(req, resp); 
   }

}

Writing request processing logic in doXxx(-,-) is an industry-standard approach, therefore it is not recommended to use the service(-,-) method to process the request.

Example

Description:- Develop a Servlet-based web application to check whether a user is eligible for voting or not. Take an HTML form, and get input from the user. Based on the entered age check he/she is eligible for voting or not? Display the appropriate message to the end-user. Assume 18 is the minimum age for voting. 

Deployment directory structure for the web application,

VotingApp
   |=> WEB-INF
      |=> web.xml
      |=> classes
         |=> CheckVoterServlet.java
   |=> home.html

The HTML form (home.html),

<div>
   <form action='checkvoter' method="POST">
    Person Name:: <input type="text" name="pname"><br><br>
    Person Age:: <input type="password" name="page"><br><br>
    <input type="submit" value="Check Voting Eligibility">
</div>
Simple HTML Form Example

The servlet web component (CheckVoterServlet.java),

//  CheckVoterServlet.java
package com.kp.servlet;

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

public class CheckVoterServlet extends HttpServlet {

   // Method to handle POST method request
   @Override
   public void doPost(HttpServletRequest req, HttpServletResponse res) 
               throws ServletException, IOException {

       // declare variables
       PrintWriter pw = null;
       String name = null;
       String tage = null;
       int age = 0;

       // set content type
       res.setContentType("text/html");

       // get PrintWriter object
       pw = res.getWriter();

       // get form data (from req parameter)
       name = req.getParameter("pname");
       tage = req.getParameter("page");

       // convert String value to int
       age = Integer.parseInt(tage);

       // check age
       pw.println("<h1 style='text-align: center; color:blue'>"
                 + "Hello "+ name + "</h1>");
       if(age < 18) {
          pw.println("<h2 style='text-align: center; color:red'>"
                    +"You are not eligible for voting.</h2>"
                    +"<h3 style='text-align: center; color:green'>"
                    +"Please wait for more " + (18-age) + " years.<br>"
                    +" Thank You.<h3>"
          );
       } else  {
          pw.println("<h2 style='text-align: center; color:green'>"
                    +"You are eligible for voting.</h2>"
                    +"<h3 style='text-align: center'>"
                    +"Thank You.<h3>"
          );
       }

       // close stream
       pw.close();
   }

   // Method to handle GET method request
   @Override
   public void doGet(HttpServletRequest req, HttpServletResponse res) 
               throws ServletException, IOException {
       // call doPost() method
       doPost(req, res);
   }
}

The web.xml file,

<web-app>
   <servlet>
      <servlet-name>vote</servlet-name>
      <servlet-class>com.kp.servlet.CheckVoterServlet</servlet-class>
   </servlet>
   <servlet-mapping>
      <servlet-name>vote</servlet-name>
      <url-pattern>/checkvoter</url-pattern>
   </servlet-mapping>
</web-app>

See the source code of this web application at GitHub. Give request to the home.html through http://localhost:8080/VotingApp/home.html

In the welcome file list, we will see how to configure this home.html page as a welcome page or homepage of the web application. Currently, whenever we give a request to http://localhost:8080/VotingApp/ then we are getting 404 errors. But after welcome file configuration, the home.html will be displayed.

Servlet containers don’t call doGet(-,-) or doPost(-,-) method directly on our servlet component, they will be called through the service(-,-) method of the superclass (HttpServlet class). It means HttpServlet class internally calls the doGet(-,-) method for the GET mode request and calls the doPost(-,-) for POST mode request.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *