Servlet vs JSP: Key Differences Explained

Servlet vs JSP: Key Differences Explained

A servlet is a Java class that runs on a web server and generates a response to an HTTP request. A JSP (Jakarta Server Pages, formerly JavaServer Pages) is an HTML page with embedded Java expressions and tags. The server converts each JSP into a servlet before running it.

The difference between a servlet and a JSP is therefore one of role and writing style, not capability:

  • Servlets are Java code that produces HTML. They suit request handling and control logic.
  • JSPs are HTML that contains Java-based tags. They suit page layout and display.

Both technologies are specifications of Jakarta EE, the enterprise Java platform maintained by the Eclipse Foundation since Oracle transferred Java EE in 2017. The current platform, Jakarta EE 11 (released June 2025), includes Jakarta Servlet 6.1 and requires Java 17 or later. Apache Tomcat 11 is the reference container for running both.

Servlets and JSP remain core topics in Java fresher interviews because every Java web framework, including Spring MVC and Spring Boot, runs on the Servlet API.

This guide covers the difference between servlets and JSP, whether a JSP is a servlet, the same page written both ways, how they work together in MVC, javax vs jakarta, and whether they are still used in 2026.

Quick answer: what is the difference between a servlet and a JSP? A servlet is a Java class that handles requests and business logic, writing HTML from Java code. A JSP is an HTML page with tags and expressions that the container compiles into a servlet. Servlets act as the controller in MVC, and JSP acts as the view.

Table of contents

  1. What Are Servlets and JSP?
  2. Servlet vs JSP – Key Differences
  3. Servlet vs JSP Example – The Same Page Written Both Ways
  4. How Servlets and JSP Work Together in MVC
  5. Are Servlets and JSP Still Used in 2026?
  6. Servlet and JSP Interview Questions for Freshers
  7. Learn Java Web Development at Cyber Success
  8. Frequently Asked Questions

What Are Servlets and JSP?

Servlets and JSP are the two original Java technologies for building dynamic web pages. Servlets handle the request; JSP renders the response page.

What is a servlet?

A servlet is a Java class that extends HttpServlet and runs inside a servlet container such as Apache Tomcat. The container receives each HTTP request, calls the servlet’s doGet() or doPost() method, and sends the servlet’s output back to the browser. A servlet container, also called a web container, manages the servlet lifecycle and creates a thread for each request.

Servlet lifecycle (5 steps)

  1. Load class: the container loads the servlet class, either on the first request or at startup.
  2. Create instance: one instance is created and shared by all requests.
  3. init(): this runs once, for set-up such as reading configuration.
  4. service(): this runs for every request and dispatches to doGet(), doPost() and the other handler methods.
  5. destroy(): this runs once before the servlet is removed, to release resources.

What is a JSP?

A JSP (Jakarta Server Pages) is a text file, usually HTML, containing JSP elements:

  • directives (<%@ page %>)
  • Expression Language (${…})
  • JSTL tags (<c:forEach>)
  • scriptlets (<% %>), which are discouraged

The container’s JSP engine (Jasper, in Tomcat) translates the page into a servlet the first time it is requested.

JSP lifecycle (7 steps)

  1. Translation: jsp is converted into a Java servlet source file.
  2. Compilation: the generated source is compiled into a .class
  3. Class loading: the container loads the class.
  4. Instantiation: an instance of the generated servlet is created.
  5. jspInit(): this runs once.
  6. _jspService(): this runs for every request. It is generated from the page and cannot be overridden.
  7. jspDestroy(): this runs once before removal.

Is JSP a servlet?

Yes. Every JSP becomes a servlet at runtime. The container translates the JSP into a Java class that implements the servlet interface (in Tomcat it extends HttpJspBase, which extends HttpServlet), then compiles and runs it like any other servlet. JSP is a more convenient way to write a servlet whose main job is producing HTML.

javax vs jakarta servlet: what changed?

The servlet package name changed from javax.servlet to jakarta.servlet in Jakarta EE 9 (2020), after Oracle transferred Java EE to the Eclipse Foundation without the rights to the javax namespace. The API is functionally the same; only the import statements differ.

 

javax.servlet

jakarta.servlet

Platforms

Java EE 8 and earlier, Jakarta EE 8

Jakarta EE 9, 10 and 11

Servlet versions

Servlet 4.0 and earlier

Servlet 5.0, 6.0 and 6.1

Tomcat versions

Tomcat 9 and earlier

Tomcat 10 and 11

Spring versions

Spring Boot 2.x, Spring Framework 5

Spring Boot 3 and 4, Spring Framework 6 and 7

Example import

import javax.servlet.http.HttpServlet;

import jakarta.servlet.http.HttpServlet;

Code written with javax.servlet will not compile against Tomcat 10 or later, or Spring Boot 3 or later, until its imports are changed to jakarta.servlet.

Servlet vs JSP – Key Differences

The key difference between a servlet and a JSP is the direction of the code. A servlet is Java code that writes HTML, while a JSP is HTML that contains Java-based tags. A JSP still compiles into a servlet, so both run at the same speed once the JSP has been compiled.

Factor

Servlet

JSP

What it is

A Java class extending HttpServlet

A text/HTML page with JSP elements, translated into a servlet

Written as

Java code that outputs HTML with PrintWriter

HTML with Expression Language (${}), JSTL tags and directives

Best used for

Request handling, validation, business logic, redirects

Displaying data as HTML pages

Role in MVC

Controller

View

File extension

.java, compiled to .class

.jsp (translated and compiled by the container)

First-request speed

No translation step

Slower first request while the page is translated and compiled; later requests are equivalent

Recompilation after changes

Rebuild and redeploy the class

The container detects the changed .jsp and recompiles it automatically in development mode

Implicit objects

None. You obtain request, response and session from method parameters

Nine built in: request, response, session, application, out, config, pageContext, page, exception

Session handling

Call request.getSession() explicitly

A session is available by default (session=”true”)

Custom tags

Not applicable

Supports JSTL and custom tag libraries

Overridable request method

service(), doGet() and doPost() can be overridden

_jspService() is generated and cannot be overridden

Protocols

Generic servlets can serve any request/response protocol; HttpServlet serves HTTP

Built on HttpServlet, so HTTP

Readability for designers

Low, because HTML sits inside Java strings

High, because the file looks like HTML

When to use a servlet: to process form submissions, call services or databases, check login, and decide which page to show.

When to use a JSP: to display the result. Keep Java logic out of JSPs and use Expression Language and JSTL instead of scriptlets.

Servlet vs JSP Example – The Same Page Written Both Ways

The clearest way to see the difference between a servlet and a JSP is to build the same page twice. Both examples below read a name parameter from the URL and display a greeting. For example, /hello?name=Priya shows “Hello, Priya!”, and with no name it shows “Hello, Guest!”.

As a servlet (HelloServlet.java)

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import java.io.IOException;

@WebServlet(“/hello”)
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String name = req.getParameter(“name”);
        resp.setContentType(“text/html;charset=UTF-8”);
        resp.getWriter().println(“<html><body><h1>Hello, “
            + (name != null ? name : “Guest”) + “!</h1></body></html>”);
    }
}

As a JSP (hello.jsp)

<%@ page contentType=”text/html;charset=UTF-8″ %>
<%@ taglib prefix=”c” uri=”jakarta.tags.core” %>
<html><body>
  <h1>Hello, <c:out value=”${empty param.name ? ‘Guest’ : param.name}”/>!</h1>
</body></html>

What the comparison shows

  • The servlet needs a class, imports, a method and HTML written inside Java strings. Adding layout means editing Java code.
  • The JSP is about four lines of markup, and designers can edit the HTML directly. ${param.name} is Expression Language, <c:out> is a JSTL tag that escapes the value safely, and no Java syntax appears on the page.
  • Security: the servlet prints the raw parameter, which is open to cross-site scripting (XSS). The JSP’s <c:out> HTML-escapes the value automatically. In real servlets, escape user input or forward to a view.
  • Mapping: @WebServlet(“/hello”) maps the servlet to a URL with no xml, using the annotation configuration available since Servlet 3.0. A JSP is mapped by its file path.

In practice, neither page is written this way in a real application. The servlet handles the request and the JSP displays the result, as the MVC section below shows.

How Servlets and JSP Work Together in MVC

In MVC (Model–View–Controller), a servlet acts as the controller and a JSP acts as the view. The servlet receives the request, prepares the data (the model) and forwards it to a JSP, which displays it. This separation was the standard design for Java web applications before Spring MVC, and Spring MVC still follows the same pattern.

MVC is a design pattern that splits an application into three parts:

  • Model: data and business logic, held in Java objects, services or JavaBeans
  • View: presentation, here the JSP
  • Controller: request handling and flow, here the servlet

The request flow, step by step

  1. The browser sends a request, for example GET /courses.
  2. The servlet (controller) mapped to /courses receives it.
  3. The servlet loads the data from a service or database. This data is the model.
  4. The servlet stores the model with setAttribute().
  5. The servlet forwards the request to the JSP with forward().
  6. The JSP (view) reads the model with Expression Language and JSTL, renders the HTML, and the container sends the response.

Servlet and JSP in MVC · request to response in 5 steps

The browser never talks to the JSP directly: every request passes through the servlet, which gathers the model before handing it to the view.

Controller (CourseController.java)

@WebServlet(“/courses”)
public class CourseController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        List<String> courses = List.of(“Java Full Stack”, “Python Full Stack”); // Model
        req.setAttribute(“courses”, courses);
        req.getRequestDispatcher(“/WEB-INF/views/courses.jsp”).forward(req, resp); // View
    }
}

View (/WEB-INF/views/courses.jsp)

<%@ taglib prefix=”c” uri=”jakarta.tags.core” %>
<ul>
  <c:forEach var=”course” items=”${courses}”>
    <li><c:out value=”${course}”/></li>
  </c:forEach>
</ul>

Placing JSPs inside /WEB-INF/ stops browsers from opening them directly, so every request must go through the controller. This MVC structure, sometimes called “Model 2”, is the direct ancestor of Spring MVC, where DispatcherServlet is the front controller and a @Controller class plays the servlet’s role.

Are Servlets and JSP Still Used in 2026? (Jakarta EE, Spring Boot, Thymeleaf)

Servlets are used everywhere in 2026, usually hidden inside frameworks. JSP is now mostly a legacy view technology, maintained in existing applications but rarely chosen for new ones. Every Spring Boot web application runs on the Servlet API, while new projects typically use Thymeleaf or a JavaScript front end instead of JSP.

Servlets: still the foundation

The Servlet API is the base layer of Java web development. Jakarta EE 11, released in June 2025 with Java 17 as its minimum, includes Jakarta Servlet 6.1, and Apache Tomcat 11 implements it. Spring MVC’s DispatcherServlet is itself a servlet, and Spring Boot embeds Tomcat by default. A developer writing a Spring @RestController is building on servlets without writing HttpServlet directly. This is why interviewers still ask about the servlet lifecycle, filters and sessions.

JSP: supported but legacy

JSP is still part of Jakarta EE as Jakarta Pages, and Tomcat still compiles it. Spring Boot, however, discourages it:

  • JSP does not work in an executable JAR with an embedded container, so applications must be packaged as a WAR.
  • The Undertow embedded server does not support JSP at all.

Spring’s documentation recommends template engines such as Thymeleaf or FreeMarker instead. Many banks, insurers and service companies in Pune still maintain large JSP-based applications, so JSP skills remain useful for support and migration work.

What replaced JSP

Approach

How it renders pages

Typical use in 2026

JSP + JSTL

Server-side, compiled to servlets

Legacy enterprise applications, maintenance

Thymeleaf

Server-side natural HTML templates

New Spring Boot server-rendered apps, admin panels

FreeMarker / Mustache

Server-side templates

Emails, reports, simple pages

Jakarta Faces (JSF)

Server-side component framework

Existing Jakarta EE enterprise apps

React or Angular + REST APIs

Client-side, in the browser

Most new web applications and full stack roles

Should freshers learn Servlets and JSP in 2026?

Yes, but briefly. Spend about 1–2 weeks on the servlet lifecycle, request and response handling, sessions, filters and the MVC flow, because these concepts explain how Spring Boot works and are common interview topics. Then move to Spring Boot and either Thymeleaf or React. The full learning order is in the Java developer roadmap 2026.

Servlet and JSP Interview Questions for Freshers

Servlet and JSP questions appear in most Java fresher interviews, especially at IT service companies. They test whether a candidate understands how Java web requests actually work beneath Spring. The 12 questions below are the most frequently asked, each with a short model answer.

  1. What is the difference between a servlet and a JSP? A servlet is a Java class that handles requests and writes the response from Java code. A JSP is an HTML page with tags that the container compiles into a servlet. A servlet acts as the controller and a JSP as the view.
  2. Is JSP a servlet? The container translates every JSP into a servlet class, compiles it and runs it like any servlet.
  3. Explain the servlet lifecycle. The container loads the class and creates one instance. init() runs once, service() runs for every request and dispatches to doGet() or doPost(), and destroy() runs once before the servlet is removed.
  4. What is the difference between doGet() and doPost()? doGet() handles GET requests, where parameters appear in the URL; use it to read data. doPost() handles POST requests, where parameters are sent in the request body; use it for form submissions and data changes.
  5. What is the difference between forward() and sendRedirect()? forward() passes the same request to another resource on the server, so the URL does not change and request attributes are kept. response.sendRedirect() tells the browser to make a new request, so the URL changes and request attributes are lost.
  6. Are servlets thread-safe? Not automatically. The container uses one servlet instance for many concurrent requests, so instance variables are shared. Keep request data in local variables.
  7. What are the implicit objects in JSP? There are nine: request, response, session, application, out, config, pageContext, page and exception.
  8. What is the difference between <%@ include %> and <jsp:include>? The directive <%@ include %> copies the file in at translation time, which is a static include. The action <jsp:include> includes the other resource’s output at request time, which is a dynamic include.
  9. What are the ways to manage sessions in servlets? HttpSession, cookies, URL rewriting and hidden form fields. HttpSession is the standard approach.
  10. What is a servlet filter? A class implementing servlet.Filter that runs before and after a request reaches a servlet. It is used for logging, authentication, compression and character encoding.
  11. What is the difference between servlet and jakarta.servlet? They are the same API under different package names. javax is used up to Java EE 8 and Tomcat 9; jakarta is used from Jakarta EE 9 onward, Tomcat 10 and later, and Spring Boot 3 and later.
  12. Why should you avoid scriptlets in JSP? Scriptlets (<% %>) mix Java logic into the view, which makes pages hard to read, test and maintain. Use Expression Language and JSTL, and keep logic in servlets or services.

After these, interviewers usually move to Spring Boot and Hibernate. Prepare those with Hibernate vs JDBC and Spring Boot interview questions.

Learn Java Web Development at Cyber Success, Pune

The Java Full Stack course in Pune at Cyber Success teaches Servlets and JSP as the foundation for Spring Boot, Hibernate and React, using hands-on MVC projects. The course includes mock interviews on the questions above and placement assistance at the Deccan and Karve Nagar centres.

Call +91 9168665644 or email hello@cybersuccess.biz to book a free counselling session.

Related reading

Frequently Asked Questions

What is the difference between a servlet and a JSP?

A servlet is a Java class that processes requests and generates responses from Java code. A JSP is an HTML-based page with tags and expressions that the container compiles into a servlet. Servlets handle control logic and JSPs handle presentation.

Is JSP a servlet?

Yes. Every JSP is translated into a servlet class by the container (Jasper in Tomcat), compiled, and then executed like a normal servlet.

Which is faster, a servlet or a JSP?

After the first request they run at the same speed, because a JSP is compiled into a servlet. Only the first request to a JSP is slower, while the page is translated and compiled. Containers can precompile JSPs to remove even that delay.

What is the role of servlets and JSP in MVC?

In MVC, the servlet is the controller. It receives the request, loads the model data and forwards it. The JSP is the view, which renders that data as HTML. Spring MVC follows the same pattern with DispatcherServlet and template views.

What is the difference between javax.servlet and jakarta.servlet?

They are the same Servlet API under different package names. javax.servlet is used up to Java EE 8 and Tomcat 9. jakarta.servlet is used from Jakarta EE 9 (2020) onward, including Tomcat 10 and 11 and Spring Boot 3 and 4.

Are servlets and JSP still used in 2026?

Servlets are used in every Spring Boot web application, because Spring MVC runs on the Servlet API. JSP is mainly found in existing enterprise applications. New projects usually use Thymeleaf or a React or Angular front end.

Can a JSP work without a servlet?

No. A JSP always runs as a servlet inside a servlet container, so it needs a container such as Tomcat. In an MVC application, a controller servlet usually prepares the data before forwarding to it.

Should freshers learn servlets and JSP before Spring Boot?

Yes, briefly. One to two weeks on servlets, the request lifecycle, sessions and the MVC flow makes Spring Boot easier to understand, and these topics are common in Java fresher interviews.

What should I learn after servlets and JSP?

Learn JDBC and SQL, then Spring Boot (REST APIs, Spring Data JPA and Hibernate, Spring Security), and then a view technology: either Thymeleaf or React/Angular for full stack roles.