A Servlet is a Java class that handles HTTP requests on a web server - it is the foundational building block that frameworks like Spring MVC are built on top of.

A basic servlet

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        String name = request.getParameter("name");
        if (name == null) {
            name = "Guest";
        }
        response.getWriter().println("<h1>Hello, " + name + "!</h1>");
    }
}

Visiting /hello?name=Riya triggers doGet(), reads the name query parameter, and writes an HTML response - conceptually the same thing $_GET does in PHP.

The servlet lifecycle

A servlet container (like Apache Tomcat) manages the servlet's lifecycle: init() runs once when the servlet is first loaded, service() (which dispatches to doGet/doPost/etc.) runs for every request, and destroy() runs once when the container shuts the servlet down. You rarely override init()/destroy() directly - doGet and doPost are where the real work happens.

Handling form submissions with doPost

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String email = request.getParameter("email");
    // validate, save to database, etc.
    response.sendRedirect("thank-you.html");
}

Writing raw servlets teaches you what is actually happening under the hood - which is exactly what makes frameworks like Spring click once you get there.