doPost
method in a servlet is designed to handle HTTP POST requests, typically used for submitting form data, while the doGet
method handles HTTP GET requests, often used to retrieve data. In this tutorial, we'll create a simple application that collects student form data using the doPost
method, stores it in memory, and retrieves it using the doGet
method.Prerequisites
Before starting, ensure you have:
- Basic understanding of Java Servlets and JSP.
- Java web application development environment set up (e.g., Apache Tomcat).
- Maven for managing project dependencies.
Project Structure
Here's what our project structure will look like:
student-form/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── example/
│ │ │ └── servlet/
│ │ │ └── StudentServlet.java
│ │ ├── resources/
│ │ └── webapp/
│ │ ├── index.jsp
│ │ └── studentDetails.jsp
└── pom.xml
Dependencies
Add the necessary dependencies to your pom.xml
file for the latest versions of JSP and servlet APIs:
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jakarta.servlet.jsp.jstl</groupId>
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
<version>3.0.0</version>
</dependency>
Creating the JSP Form Page
First, let's create a JSP page index.jsp
that will collect student data:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<title>Student Registration Form</title>
</head>
<body>
<h2>Student Registration Form</h2>
<form action="student" method="post">
<label for="firstName">First Name:</label>
<input type="text" id="firstName" name="firstName" required><br><br>
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" name="lastName" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Submit">
</form>
<h2>Retrieve Student Data</h2>
<form action="student" method="get">
<label for="retrieveEmail">Email:</label>
<input type="email" id="retrieveEmail" name="email" required><br><br>
<input type="submit" value="Retrieve">
</form>
</body>
</html>
Creating the Servlet to Handle Requests
Next, we'll create a servlet named StudentServlet.java
to handle the POST and GET requests. We'll use an in-memory data structure to store the student data:
package com.example.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@WebServlet("/student")
public class StudentServlet extends HttpServlet {
private Map<String, Student> studentDatabase = new HashMap<>();
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Retrieve form data from the request
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String email = request.getParameter("email");
String password = request.getParameter("password");
// Store data in memory
Student student = new Student(firstName, lastName, email, password);
studentDatabase.put(email, student);
// Set attributes to request object
request.setAttribute("message", "Student data has been saved successfully!");
// Forward to JSP page to display the details
request.getRequestDispatcher("index.jsp").forward(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Retrieve email from request parameters
String email = request.getParameter("email");
// Get student data from memory
Student student = studentDatabase.get(email);
// Set attributes to request object
if (student != null) {
request.setAttribute("firstName", student.getFirstName());
request.setAttribute("lastName", student.getLastName());
request.setAttribute("email", student.getEmail());
request.setAttribute("password", student.getPassword());
} else {
request.setAttribute("message", "No student found with the provided email.");
}
// Forward to JSP page to display the details
request.getRequestDispatcher("studentDetails.jsp").forward(request, response);
}
}
Creating the JSP Page to Display Details
Create another JSP page studentDetails.jsp
to display the student details:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<title>Student Details</title>
</head>
<body>
<h2>Student Details</h2>
<c:if test="${not empty message}">
<p>${message}</p>
</c:if>
<c:if test="${not empty firstName}">
<p>First Name: ${firstName}</p>
<p>Last Name: ${lastName}</p>
<p>Email: ${email}</p>
<p>Password: ${password}</p>
</c:if>
</body>
</html>
Explanation of the doPost
and doGet
Methods
Handling POST Requests (doPost method):
- The
doPost
method retrieves form data using theHttpServletRequest
object'sgetParameter
method. - It stores the data in an in-memory
HashMap
. - Attributes are set to the request object to be forwarded to the JSP page for display.
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Retrieve form data from the request String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); String email = request.getParameter("email"); String password = request.getParameter("password"); // Store data in memory Student student = new Student(firstName, lastName, email, password); studentDatabase.put(email, student); // Set attributes to request object request.setAttribute("message", "Student data has been saved successfully!"); // Forward to JSP page to display the details request.getRequestDispatcher("index.jsp").forward(request, response); }
- The
Handling GET Requests (doGet method):
- The
doGet
method retrieves the student data from the in-memoryHashMap
based on the email parameter. - Attributes are set to the request object to be forwarded to the JSP page for display.
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Retrieve email from request parameters String email = request.getParameter("email"); // Get student data from memory Student student = studentDatabase.get(email); // Set attributes to request object if (student != null) { request.setAttribute("firstName", student.getFirstName()); request.setAttribute("lastName", student.getLastName()); request.setAttribute("email", student.getEmail()); request.setAttribute("password", student.getPassword()); } else { request.setAttribute("message", "No student found with the provided email."); } // Forward to JSP page to display the details request.getRequestDispatcher("studentDetails.jsp").forward(request, response); }
- The
Conclusion
In this tutorial, we learned how to handle form data using Java Servlets. We used the doPost
method to collect and store data, and the doGet
method to retrieve and display the data. This example demonstrates the basic concepts of handling HTTP requests in a Java web application.
Related Servlet Posts
- Servlet Life Cycle
- Servlet Interface Example
- GenericServlet Class Example
- HttpServlet Class Example Tutorial
- HttpServlet doGet() Method Example
- HttpServlet doPost() Method Example
- @WebServlet Annotation Example
- @WebInitParam Annotation Example
- @WebListener Annotation Example
- @WebFilter Annotation Example
- @MultipartConfig Annotation Example
- How to Return a JSON Response from a Java Servlet
- Servlet Registration Form + JDBC + MySQL Database Example
- Login Form Servlet + JDBC + MySQL Example
- Servlet JDBC Eclipse Example Tutorial
- JSP Servlet JDBC MySQL CRUD Example Tutorial
- Servlet + JSP + JDBC + MySQL Example
- Registration Form using JSP + Servlet + JDBC + Mysql Example
- Login Form using JSP + Servlet + JDBC + MySQL Example
- JSP Servlet Hibernate CRUD Example
- JSP Servlet Hibernate Web Application
- Hibernate Registration Form Example with JSP, Servlet, MySQL
- Login Form using JSP + Servlet + Hibernate + MySQL Example
Comments
Post a Comment
Leave Comment