HttpServlet Class in Java
HttpServlet is the base class most developers extend when building Java web applications. It provides convenient methods for each HTTP verb and integrates with the Servlet API request/response objects.
Class Hierarchy
GenericServlet → HttpServlet → YourServlet. GenericServlet is protocol-independent; HttpServlet adds HTTP-specific methods like doGet(), doPost(), doPut(), doDelete(), and doHead().
Overriding HTTP Methods
doGet()
Handles HTTP GET requests. Used for retrieving data, displaying pages. Should be idempotent and not modify server state.
doPost()
Handles HTTP POST requests. Used for form submissions, creating resources. Data is sent in the request body.
doPut() / doDelete()
Used in RESTful APIs for updating and deleting resources. Less common in traditional web forms.
doGet and doPost Example
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.getRequestDispatcher("/register.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String email = req.getParameter("email");
String name = req.getParameter("name");
// Save to database...
resp.sendRedirect("/success");
}
}Best Practices
- Never override service() unless you need custom dispatch logic.
- Set content type before writing to the response: resp.setContentType("text/html;charset=UTF-8").
- Use POST for form submissions that change data; GET for read-only operations.
- Validate and sanitize all request parameters to prevent injection attacks.
Frequently Asked Questions
What happens if I don't override doGet()?▼
HttpServlet's default doGet() returns HTTP 405 Method Not Allowed. Always override the methods your application supports.
