Servlet Tutorial for Beginners – Life Cycle, Working, Syntax & Use Cases

Author: Ritika
0

 

If you are a B.Tech student (especially CSE/IT), then you must have seen the word Servlet in your Java or Web Technology subject. I still remember when I first saw it in 3rd semester. It sounded very complicated. But honestly, once I understood how it actually works, it became one of the easiest backend concepts.

 

In simple words, Servlet is a Java program that runs on a server and handles client requests.

 

Whenever you:

  • Fill a login form
  • Submit exam registration
  • Book a train ticket online

 

There is some backend program processing your request. That backend program can be a Servlet.

 

In this blog, we will understand:

Servlet Tutorial for Beginners – Life Cycle, Working, Syntax & Use Cases
(toc) #title=(Table of Content)

 

Let’s start step by step.

 

What is a Servlet?

A Servlet is a server-side Java class used to create dynamic web applications.

It runs inside a Servlet Container like Apache Tomcat and handles HTTP requests and responses.

Exam Definition

A Servlet is a server-side Java program that processes client requests and generates dynamic responses.

 

Servlet Syntax (Very Important for Exams & Practicals)

Many students understand theory but get confused in syntax. When I first wrote my Servlet in lab, I made so many small mistakes like missing import statements.

Let’s see the basic syntax properly.

 

Basic Servlet Syntax Using HttpServlet


import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {

    // Initialization method
    public void init() throws ServletException {
        System.out.println("Servlet Initialized");
    }

    // Handles GET request
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
                         throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println("<h1>Hello Students!</h1>");
        out.println("<p>This is my first Servlet.</p>");
    }

    // Handles POST request
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
                          throws ServletException, IOException {

        String name = request.getParameter("username");

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println("<h2>Welcome " + name + "</h2>");
    }

    // Destroy method
    public void destroy() {
        System.out.println("Servlet Destroyed");
    }
}

 

Important Points in Syntax

Let’s understand what is happening here.

 

Extending HttpServlet


public class MyServlet extends HttpServlet

This means our class is inheriting features of HttpServlet.

Basically, without extending HttpServlet, it won’t behave like a Servlet.

 

@WebServlet Annotation


@WebServlet("/MyServlet")

This maps the Servlet to a URL pattern.

Instead of writing mapping in web.xml, we use annotation. It is simpler and modern.

 

doGet() Method

Used when client sends GET request.

Example:

  • Opening a webpage
  • Clicking a link

 

doPost() Method

Used when client submits form data.

Example:

  • Login form
  • Registration form

 

request and response Objects

HttpServletRequest → Used to get client data

HttpServletResponse → Used to send response

 

Many students get confused here. Just remember:

Request = Incoming data
Response = Outgoing data

 

Servlet Life Cycle

This is one of the most important theory questions.

Servlet life cycle has three main methods:

  • init()
  • service()
  • destroy()

 

init() Method

Called only once when Servlet is loaded.

Used for:

  • Database connection
  • Resource initialization

I remember this as:

init() = Setup time

 

service() Method

Called for every request.

Internally it calls:

  • doGet()
  • doPost()

So whenever user sends request, service() handles it.

 

destroy() Method

Called once before Servlet is removed.

Used to:

  • Close database connection
  • Free resources

Life Cycle Flow

  • Client sends request
  • Servlet is loaded
  • init() is called
  • service() is called for each request
  • destroy() is called when server stops

 

How Servlet Works

Let’s understand this with a simple college example.

Imagine you created a login form for your college mini project.

Step 1: User Enters Data

User enters:

  • Username
  • Password

Clicks submit.

Step 2: Request Sent to Server

Browser sends HTTP request to Tomcat server.

Step 3: Servlet Container

Servlet container:

  • Checks URL mapping
  • Finds correct Servlet
  • Calls doPost()

Step 4: Processing Logic

Inside doPost():


request.getParameter("username");

Connect to database

Validate user

Step 5: Send Response


PrintWriter out = response.getWriter();

Browser shows result.

Simple Working Diagram

Client → Server → Servlet Container → Servlet → Database → Response → Client

 

Advantages of Servlet

Now let’s see why we use it.

 

Fast Performance

Uses threads instead of creating new process like CGI.

Better for multiple users.

 

Platform Independent

Runs on any OS with JVM.

 

Secure

Java provides strong security features.

 

Scalable

Can handle many users at same time.

 

Foundation for Spring

Spring Boot internally uses Servlet API.

So learning Servlet makes backend journey easier.

 

Use Cases of Servlet

Login System

Most common use case in student projects.

Registration Forms

Storing student data into database.

Online Result Portal

Fetching marks from database.

E-commerce Websites

Handling cart and orders.

Banking Applications

Processing transactions securely.

 

Servlet vs JSP (Quick Comparison)

 

Feature Servlet JSP
Type Java Class HTML + Java
Used For Backend Logic Frontend View
Code Style More Java More HTML
Role Controller View

 

In simple words:

Servlet = Brain
JSP = Face

 

FAQs

What is Servlet Container?

It is a part of web server that manages Servlets. Example: Apache Tomcat.

What is difference between GET and POST?

GET → Data visible in URL

POST → Data hidden and more secure

Is Servlet outdated?

No. It is foundation of modern Java backend frameworks.

Can we connect database using Servlet?

Yes, using JDBC.

Is Servlet important for exams?

Yes, especially life cycle and working.

 

Conclusion

So friends, this was a complete and beginner-friendly explanation of Servlet including syntax.

When I first learned Servlet in lab, I was honestly confused. But once I built small projects like login form and student registration system, everything started making sense.

If you:

  • Understand syntax properly
  • Remember life cycle
  • Practice small programs

Then Servlet becomes very easy.

And trust me, once you master Servlet, learning Spring Boot feels much smoother.

Keep practicing, build small backend projects, and don’t just read theory.

That’s how we actually grow as engineers 🚀

 

Read Also : What is JDBC in Java? Complete Beginner Guide with Architecture & CRUD

 

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !)#days=(20)

We use cookies to personalize content and ads, provide social media features, and analyze our traffic. By clicking "Accept", you consent to our use of cookies. Privacy Policy Cookies Policy
Accept !
Breaking News | News |