The following example code shows a program to Demonstrate doGet() and doPost() Methods in a Servlet in Java.

Here is an example of a dynamic web application using servlets to demonstrate the doGet() and doPost() methods.

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

public class RequestMethodServlet extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Request Method Information</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Request Method Information</h1>");
    out.println("<p>Request Method: GET</p>");
    out.println("</body>");
    out.println("</html>");
  }

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Request Method Information</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Request Method Information</h1>");
    out.println("<p>Request Method: POST</p>");
    out.println("</body>");
    out.println("</html>");
  }
}

In this example, the RequestMethodServlet class handles both GET and POST requests. The doGet method handles GET requests and displays a message indicating that the request method is GET. The doPost method handles POST requests and displays a message indicating that the request method is POST. Both methods generate an HTML response that is sent to the client.


Further Reading

Understanding Enterprise Java Beans

Java Practice Exercise

programmingempire

Princites