Java Notes
Complete guide to HttpServlet class - HTTP-specific servlet implementation with doGet, doPost, doPut, doDelete methods and practical examples.
What is HttpServlet?
HttpServlet is an abstract class in the jakarta.servlet.http package that extends GenericServlet and provides HTTP-specific functionality. It is the primary class you extend when building Java web applications.
HttpServlet automatically parses HTTP requests and dispatches them to the appropriate handler method (doGet, doPost, doPut, doDelete, etc.).
How HttpServlet Works Internally
When a request arrives, the servlet container calls service():
// Inside HttpServlet (simplified source code)
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String method = req.getMethod();
if (method.equals("GET")) {
doGet(req, resp);
} else if (method.equals("POST")) {
doPost(req, resp);
} else if (method.equals("PUT")) {
doPut(req, resp);
} else if (method.equals("DELETE")) {
doDelete(req, resp);
} else if (method.equals("HEAD")) {
doHead(req, resp);
} else if (method.equals("OPTIONS")) {
doOptions(req, resp);
} else if (method.equals("TRACE")) {
doTrace(req, resp);
} else {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
}
}HTTP Method Handlers
| Method | Purpose | Typical Use Case |
|---|---|---|
doGet() | Retrieve data | Loading pages, fetching API data |
doPost() | Submit/create data | Form submission, creating resources |
doPut() | Update data | Updating entire resources |
doDelete() | Remove data | Deleting resources |
doPatch() | Partial update | Updating specific fields |
doHead() | Get headers only | Check if resource exists |
doOptions() | Get allowed methods | CORS preflight requests |
Complete CRUD Servlet Example
Handling Form Data
HTML Form
<form action="/register" method="POST">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="email" name="email" placeholder="Email">
<select name="role">
<option value="student">Student</option>
<option value="teacher">Teacher</option>
</select>
<button type="submit">Register</button>
</form>Servlet Processing the Form
File Upload with HttpServlet
@WebServlet("/upload")
@MultipartConfig(
maxFileSize = 1024 * 1024 * 5, // 5MB max file size
maxRequestSize = 1024 * 1024 * 10 // 10MB max request
)
public class FileUploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Part filePart = request.getPart("file");
String fileName = filePart.getSubmittedFileName();
long fileSize = filePart.getSize();
String contentType = filePart.getContentType();
// Save file to server
String uploadPath = getServletContext().getRealPath("/uploads");
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) uploadDir.mkdirs();
filePart.write(uploadPath + File.separator + fileName);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h2>File Uploaded Successfully</h2>");
out.println("<p>Name: " + fileName + "</p>");
out.println("<p>Size: " + fileSize + " bytes</p>");
out.println("<p>Type: " + contentType + "</p>");
}
}Request Forwarding and Redirecting
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if ("admin".equals(username) && "password123".equals(password)) {
// Forward (server-side) — URL doesn't change in browser
request.setAttribute("user", username);
RequestDispatcher dispatcher = request.getRequestDispatcher("/dashboard.jsp");
dispatcher.forward(request, response);
} else {
// Redirect (client-side) — URL changes in browser
response.sendRedirect("/login.html?error=invalid");
}
}
}Forward vs Redirect
| Feature | Forward | Redirect |
|---|---|---|
| URL in browser | Doesn't change | Changes to new URL |
| Server/Client | Server-side | Client-side (302 response) |
| Request attributes | Preserved | Lost |
| Speed | Faster (single request) | Slower (two requests) |
| Use case | Same application | Different application/URL |
Common Mistakes
- Not overriding any doXxx() method — Returns 405 Method Not Allowed
- Overriding service() directly — Breaks HTTP method dispatching
- Forgetting to set content type — Browser may not render correctly
- Not closing resources — PrintWriter doesn't need close, but streams do
- Calling both forward and redirect — IllegalStateException
Interview Key Points
- HttpServlet extends GenericServlet, which implements Servlet
- Never override
service()in HttpServlet — override doGet/doPost instead - HttpServlet provides HTTP-specific objects (HttpServletRequest, HttpServletResponse)
- doGet() is for idempotent operations; doPost() for state-changing operations
@MultipartConfigenables file upload handling- Forward keeps the same request; Redirect creates a new request
Summary
In this chapter, we learned about HttpServlet in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for HttpServlet.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, servlets, jsp, http
Related Java Master Course Topics