Thursday, December 4, 2025

thumbnail

Introduction to Java Servlets

 Introduction to Java Servlets


A Servlet is a Java program that runs on a server and handles HTTP requests and responses.

Servlets are part of Java EE (now Jakarta EE) and are the foundation of many Java web technologies like:


JSP (JavaServer Pages)


Spring MVC (built on top of Servlet API)


JSF


Struts


They execute inside a Servlet Container such as:


Apache Tomcat


Jetty


WildFly


GlassFish


๐Ÿงฉ What Does a Servlet Do?


A servlet:


Receives an HTTP request from the browser


Processes the request (business logic, accessing DB, etc.)


Sends back an HTTP response (HTML, JSON, text, etc.)


It’s essentially the controller in early Java web applications.


๐Ÿงฑ Servlet Lifecycle


Servlets go through 3 main phases:


1️⃣ Initialization


Executed once when the servlet loads.


public void init() { }


2️⃣ Service


Handles every request.


public void service(HttpServletRequest req, HttpServletResponse resp)


3️⃣ Destroy


Called when the server shuts down or servlet is removed.


public void destroy() { }


๐Ÿ“Œ Common HTTP Methods in Servlets


You typically override:


doGet() → Handle GET requests


doPost() → Handle POST form submissions


doPut()


doDelete()


Example:


protected void doGet(HttpServletRequest req, HttpServletResponse resp) 

        throws ServletException, IOException {

    resp.getWriter().write("Hello from Servlet!");

}


๐Ÿงช Basic Servlet Example

1. Create a Servlet

import jakarta.servlet.*;

import jakarta.servlet.http.*;

import java.io.IOException;


public class HelloServlet extends HttpServlet {


    @Override

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)

            throws ServletException, IOException {

        resp.setContentType("text/plain");

        resp.getWriter().write("Hello, world! This is a Java Servlet.");

    }

}


2. Configure the Servlet (Jakarta EE 9+)


You can configure servlets using annotations:


import jakarta.servlet.annotation.WebServlet;


@WebServlet("/hello")

public class HelloServlet extends HttpServlet { ... }



This maps the servlet to:


http://localhost:8080/your-app/hello


3. Deploy to a Servlet Container


Most common container → Apache Tomcat


Steps:


Package app as a WAR file


Deploy WAR to Tomcat’s webapps/ directory


Start Tomcat


Access via browser


๐Ÿ“ฆ Servlet Request & Response Objects

HttpServletRequest


Provides data from the client:


Query parameters (req.getParameter("name"))


Headers (req.getHeader("User-Agent"))


Cookies


Session management


Request body


HttpServletResponse


Allows you to:


Write output


Set status codes


Add headers


Send redirects (resp.sendRedirect("/login"))


Set cookies


๐Ÿช Cookies & Sessions in Servlets


Servlets make session tracking easy via:


Setting a session attribute:

HttpSession session = req.getSession();

session.setAttribute("user", "John");


Retrieving a session attribute:

String user = (String) session.getAttribute("user");



Cookies are also supported via the Cookie class.


๐Ÿงฎ Forwarding vs Redirect

Forward (server-side)

req.getRequestDispatcher("home.jsp").forward(req, resp);



URL doesn’t change


Faster (no extra trip to client)


Redirect (client-side)

resp.sendRedirect("/login");



URL changes


Used for form resubmissions, login flows


๐Ÿงฐ Why Servlets Are Still Important Today


Even though frameworks like Spring Boot dominate modern development, servlets remain essential because:


Spring MVC and other frameworks are built on top of the Servlet API


Understanding servlets helps you understand how Java web requests work


Many legacy enterprise systems still use Servlets


Good interview topic for Java backend roles


๐Ÿ”š Summary


Servlets are the foundation of Java web development.

They:


Run inside servlet containers


Handle HTTP requests


Produce dynamic responses


Manage sessions, parameters, cookies


Form the core of modern frameworks like Spring

Learn Full Stack JAVA Course in Hyderabad

Read More

๐Ÿ”™ Backend Development with Java

Java Best Practices for Clean Code

Access Modifiers and Encapsulation in Java

Understanding JVM, JRE, and JDK

Visit Our Quality Thought Institute in Hyderabad

Get Directions


Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive