Prof. (Dr. ) Harish Kumar MittalProfessor · Researcher · Educator

Project Based Learning in Java

Servlets and JSP

A servlet is a Java component that receives web requests and produces responses. A servlet container, such as Tomcat, manages its execution. JavaServer Pages (JSP), now Jakarta Server Pages, is a template technology for generating web pages on the server. In the examples, the servlet handles the request and the JSP displays the result.

Follow a web request from the servlet controller to the JSP view, and build a server-rendered page.

Part 1: Servlets and the Web Request Lifecycle

Key concepts

Servlet
A Java component that receives requests and produces responses under a servlet container.
Container
The runtime that creates the servlet and calls its lifecycle and request-handling methods.
HTTP
Hypertext Transfer Protocol: the rules for exchanging web requests and responses.
Concurrency
Overlapping execution of several tasks, such as requests from different learners.

Read the application as a sequence: browser sends input → container chooses the servlet → servlet calls the required operation → server sends a response. The browser does not call a Java method directly. The container connects the web request to that method.

Example: Asha and Ravi may submit forms at the same time. A local variable inside doPost belongs to that invocation. An instance field on the servlet may be shared, so it must not hold the current learner’s name.

Explain how a servlet container processes requests and write a request-safe servlet.

Chapter 3.1 · Lesson 1 CO5 aligned Unit 3 · Chapter 3.1

Course Outcome (CO) states what a learner should be able to do after the course; CO1 to CO5 label the five syllabus outcomes.

Learning outcome: Explain how a servlet container processes requests and write a request-safe servlet.

JavaServer Pages (JSP) is the original name of Jakarta Server Pages, a template technology that generates web content on the server.

Start here: Follow one request first: GET displays the form; POST sends its name parameter. The servlet validates that input and sets the studentName request attribute for the JSP. Then study lifecycle and shared state, and build the complete example.

Introduction

Hypertext Transfer Protocol (HTTP) defines how a client sends a request and a server returns a response on the web.

A web application lets a browser or another HTTP client request a service over the web. In a Java web application, code on the server receives each request, applies the application rules and sends a response.

Unlike a simple console program, a web application can serve several users at the same time. Each request must keep its own input separate from other requests.

A servlet is a Java server-side component that implements the Servlet contract and runs under the control of a servlet container. For HTTP applications, a servlet commonly extends HttpServlet and handles requests through methods such as doGet() and doPost(). Typical uses include processing a form, retrieving records through a service, checking input and selecting a response or view.

This lesson establishes the request–response model before introducing servlet code. It builds on classes, inheritance, exceptions and multithreading from the earlier units.

Learning objectives

After completing this lesson, you should be able to:

  1. Define a servlet, servlet container, HTTP request and HTTP response.
  2. Identify the parts of a web address and explain servlet mapping.
  3. Describe initialisation, request processing and destruction in the servlet lifecycle.
  4. Distinguish request parameters, attributes and session state.
  5. Explain why request-specific data must not be shared through servlet fields.

Key terms and definitions

HyperText Markup Language (HTML) structures a web page using elements such as headings, paragraphs, links and forms. Uniform Resource Locator (URL) is a resource identifier that describes where a resource can be accessed and the scheme used to access it.

Term Definition Example or significance
Client A program that sends a request to a server. A browser submitting a student form.
Server A program or system that receives requests and provides responses. A Java application running in Tomcat.
HTTP Hypertext Transfer Protocol: an application-level protocol defining the meaning of web requests and responses. GET requests a representation; POST submits data for processing.
HTTP request A message containing a method, target, headers and, when applicable, a body. A POST carrying a student's name.
HTTP response A message containing a status code, headers and, when applicable, a body. 200 with an HTML page, or 400 for invalid input.
Web server Software that handles HTTP communication and serves or delegates requests. It may serve a static file or pass a dynamic request to an application.
Servlet container Runtime infrastructure that loads servlets, manages their lifecycle and invokes them for matching requests. Tomcat provides this environment.
Servlet mapping The association between a URL pattern and a servlet. @WebServlet("/student").
Context path The URL path prefix identifying a deployed web application. /pblj-web in the chapter example.
Request parameter A string value supplied through a query string or supported form submission. The name field read by getParameter().
Request attribute A named Java object associated with a request by server-side code. studentName, passed to the JSP.
Session A container-managed association that can retain state across related requests. Accessed through HttpSession; it is separate from one request.

HTTP is stateless: the protocol does not inherently retain an application's conversation between independent requests. A session provides an application-level way to relate requests, commonly using a session identifier carried in a cookie. Having a session does not by itself establish a user's identity or permissions.

Position of a servlet in a web application

A web server and a servlet container describe different responsibilities, although one product can perform both. Tomcat accepts HTTP requests and provides servlet-container services. A static HTML file can be returned without servlet business logic; a dynamic response is produced using application data or processing.

Application Programming Interface (API) defines the operations one software component can use to communicate with another.

The Servlet API defines the Servlet interface. GenericServlet is a protocol-independent abstract implementation, and HttpServlet extends it with HTTP-specific behaviour. Application code normally extends HttpServlet rather than implementing every Servlet method directly.

Data Access Object (DAO) is a component that separates database operations from business logic.

The controller servlet coordinates a request; a service applies business rules, and a DAO or repository accesses stored data. Keeping these roles separate makes the application easier to test and maintain.

Browser → Container → Servlet → Service/DAO → Database
Browser ← HTTP response ← Servlet

In http://localhost:8080/pblj-web/student, the host is localhost, the port is 8080, /pblj-web is the context path and /student is the servlet mapping. The HTTP method is separate from the path: GET and POST can reach different methods on the same servlet.

Web application tiers

A typical application has a client tier, a web/application tier and a data tier. A tier is a deployment responsibility; a layer is a logical division of code. Controller, service and DAO layers can run within the same application tier. A larger deployment can separate web and business services into additional tiers.

Java Database Connectivity (JDBC) is Java's standard interface for connecting to relational databases, issuing statements and reading results. Object-Relational Mapping (ORM) maps objects in a program to rows and relationships in a database.

Tier Responsibility Chapter example
Client Submit requests and display results Browser and form
Web/application Handle HTTP and apply application rules Tomcat, servlet and service
Data Store persistent records Database reached through JDBC or ORM

Enterprise Edition (EE) identifies the enterprise Java platform; Java EE evolved into Jakarta EE for server-side applications.

Historical Java EE diagrams may also show Enterprise JavaBeans (EJB). EJB is a separate enterprise component technology; it is not required to run the servlet or Spring examples here.

CGI (Common Gateway Interface) is an interface through which a web server invokes an external program to generate a response. It is not a scripting language. Traditional CGI commonly starts a process per request. Servlets normally reuse managed instances and process requests with container-managed threads. Performance depends on the implementation and workload, but avoiding repeated process startup was an important motivation for servlet technology.

Servlet mapping and deployment configuration

@WebServlet("/student") maps a path to the class. The browser requests the mapped URL, not a downloadable .class file. A deployment descriptor named WEB-INF/web.xml is an alternative place for servlet and mapping configuration; annotation-based applications need not declare every mapping there.

The container may create and initialise a servlet when its first request arrives. It can also initialise it when the application starts, using a setting such as loadOnStartup. In either case, initialisation happens before that instance serves requests.

The URL mapping chooses the servlet; the HTTP method chooses the handler. GET commonly retrieves a page, while POST submits data for processing. Choose the method for the operation; the two methods are not interchangeable.

Compare static and dynamic responses

Static resource: GET /index.html

  1. BrowserRequests the resource
  2. Web serverFinds an existing file
  3. ResponseReturns the file content with HTTP headers

The application does not need to calculate the page content for this request. Caching and conditional requests can affect what is transferred.

Dynamic response: GET /grades

JavaScript Object Notation (JSON) is a text format for exchanging values such as objects, arrays, strings, numbers and booleans.

  1. BrowserRequests grades
  2. Servlet and serviceValidate and process the request
  3. ResponseReturn generated HTML or JSON

Processing can use request data and stored records. A database call is optional, not a requirement for every dynamic response.

Servlet lifecycle and request concurrency

The container creates the servlet and calls init() before serving requests. The service() method dispatches HTTP requests to methods such as doGet() and doPost(). Before taking the servlet out of service, the container calls destroy(). Initialisation is not repeated for every request.

One servlet instance can process concurrent requests. Keep the current student's name, request parameters and per-request JDBC connection out of instance fields. Local variables belong to the current invocation; shared mutable fields need a separate concurrency design.

API Purpose
HttpServletRequest Parameters, headers, attributes and session access
HttpServletResponse Status, headers and response body
getParameter("name") Read a submitted string; may return null
setAttribute(...) Pass a Java object within the request
getSession() Access or create a session across requests

Request attributes last for the request and survive a server-side forward. Session attributes can span several requests from the same session. Servlet-context attributes are shared across the application. Choose the shortest suitable lifetime; session state is not a substitute for authentication or validation.

Servlet lifecycle walkthrough

Follow each stage and read what the container does.

  1. ConstructCreate the servlet instance.
  2. InitialiseCall init() once for this instance.
  3. Process requestsCall service() for each request.
  4. DestroyCall destroy() before removal.

The container constructs the servlet at startup or on first use, depending on deployment configuration.

Worked servlet

The following complete class is in the Servlet/JSP project. It uses Java 17 and Jakarta Servlet 6.0.

package edu.pblj.web;

import java.io.IOException;
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("/student")
public class StudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/student.jsp").forward(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String name = request.getParameter("name");
        if (name == null || name.isBlank() || name.trim().length() > 80) {
            response.sendError(400, "Name must contain 1 to 80 characters");
            return;
        }
        request.setAttribute("studentName", name.trim());
        request.getRequestDispatcher("/WEB-INF/student.jsp").forward(request, response);
    }
}

Read the two handlers separately:

  1. doGet() forwards to the JSP so the browser can display the form.
  2. doPost() sets the character encoding before reading the submitted name.
  3. Invalid input returns HTTP 400 and stops processing. Valid input becomes the studentName request attribute.
  4. The servlet forwards the same request to the JSP, which displays the greeting. This happens inside the server; the browser URL stays the same.

The parameter is the submitted string; the attribute is the validated value passed from Java code to the view.

Build and run

Use the downloaded Servlet/JSP project:

Web Application Archive (WAR) packages a Java web application for deployment to a compatible servlet container.

  1. Extract the ZIP and open a terminal in the folder containing pom.xml.
  2. Run mvn package to build target/pblj-web.war.
  3. Copy that WAR into Tomcat 10.1's webapps directory and start Tomcat.
  4. Open http://localhost:8080/pblj-web/student in a browser.
  5. Enter Asha and submit the form. The page should display Hello, Asha.

Part 2 explains how the JSP produces that greeting.

The servlet API uses Maven scope provided because the container supplies it at runtime. A servlet is not a class to launch directly with java StudentServlet. Modern Jakarta containers use jakarta.servlet.*; older examples may use javax.servlet.*. Do not mix those API families.

Common mistakes

  • Storing a user's form values in servlet fields.
  • Writing or flushing response content before forwarding the response.
  • Assuming browser form validation makes server-side validation unnecessary.
  • Confusing a request parameter with a Java object set as a request attribute.

Summary

A servlet is a container-managed Java component. HTTP supplies the request–response protocol, while the container manages dispatch and lifecycle. Keep request data local, use the appropriate state scope and delegate business and persistence operations to other layers.

Practice

  1. Add a department parameter and pass it to the JSP.
  2. Compare request, session and application scope.
  3. Trace lifecycle calls for ten requests reaching one servlet instance.

Quick check

Check your understanding

Does every request get a fresh servlet instance? Not normally. A container can invoke one instance concurrently; keep request data separate.

Further reading

Review questions

1. Two requests arrive at one servlet. Must the container create two servlet objects?

Answer: No. One managed instance can handle concurrent requests. Keep request-specific values in the request or local variables.

2. Which method normally reads a submitted HTML form value: getParameter or setAttribute?

Answer: getParameter reads the submitted value. setAttribute stores a Java object on the server-side request for later processing or a view.

Part 2: JSP and MVC for Server-rendered Pages

Key concepts

JSP
JavaServer Pages, now Jakarta Server Pages: a server-side page-template technology.
MVC
Model–View–Controller: separate application data/rules, presentation and request coordination.
EL
Expression Language: expressions such as ${studentName} that read values in a page.
Escaping
Representing special characters as data so they are not interpreted as markup in the chosen output context.

Follow one name rather than memorising three layers. The servlet accepts and validates the name, places it in the request, and forwards to the JSP. The JSP displays that value as part of HTML. The browser receives the resulting HTML, not the JSP source or Java objects.

Example: For input <b>Asha</b>, escaped output displays the angle brackets and letters. It must not create a bold element. A forward keeps the same request attributes; a redirect starts another request.

JavaServer Pages (JSP) is the original name of Jakarta Server Pages, a template technology that generates web content on the server. Model-View-Controller (MVC) separates application data and rules, user-facing presentation, and request or input handling.

Separate request handling from presentation and explain forwarding, redirection and escaped output.

Chapter 3.1 · Lesson 1 CO5 aligned Unit 3 · Chapter 3.1

Learning outcome: Separate request handling from presentation and explain forwarding, redirection and escaped output.

Start here: Continue the same student form from Part 1. Identify the Controller, Model and View, follow the name into the JSP, then compare forwarding with redirecting.

Introduction

HyperText Markup Language (HTML) structures a web page using elements such as headings, paragraphs, links and forms.

A greeting page has two parts: fixed HTML, such as headings and form controls, and changing data, such as a student's name. Writing every HTML tag inside Java output statements soon becomes hard to read. A JSP keeps the page layout in a template and inserts the data supplied by the servlet.

JSP (JavaServer Pages) is a server-side technology for producing dynamic web content from a template containing static text, Expression Language and tags. The Jakarta EE 10 version used in this chapter is named Jakarta Server Pages 3.1. The JSP container translates the page into a servlet and executes it on the server. The browser receives the resulting content, usually HTML.

This lesson explains how JSP fits into Model–View–Controller (MVC) architecture. It continues the student-form example from Part 1 and assumes familiarity with requests, responses, parameters and attributes.

JSP terminology: JavaServer Pages and Jakarta Server Pages

Naming note: JSP stands for JavaServer Pages. Its Jakarta successor is called Jakarta Server Pages (also shortened to Jakarta Pages), not Server Page. Earlier Java EE examples use javax.servlet.jsp. This chapter uses Jakarta EE 10, Jakarta Server Pages 3.1 and jakarta.servlet.jsp on Tomcat 10.1. The .jsp extension is unchanged; these names refer to the same technology lineage.

Learning objectives

After completing this lesson, you should be able to:

  1. Define JSP and explain how a JSP page becomes a response.
  2. Identify the Model, View and Controller in a servlet-based application.
  3. Recognise JSP directives, Expression Language and tag-library elements.
  4. Distinguish forwarding from redirection and explain their effect on request data.
  5. Display untrusted text with appropriate output escaping.

Key terms and definitions

Structured Query Language (SQL) is the language used to define, query and change data in relational databases. Expression Language (EL) is the expression syntax used by page technologies to read values and invoke supported operations. JavaServer Pages Standard Tag Library (JSTL) provides reusable tags for page tasks such as iteration and escaped output; its current Jakarta name is Jakarta Tags. Uniform Resource Locator (URL) is a resource identifier that describes where a resource can be accessed and the scheme used to access it.

Term Definition Example or significance
JSP page A JavaServer Pages / Jakarta Server Pages template processed by a JSP container to generate response content. student.jsp renders a greeting.
Template A document containing a fixed structure and placeholders or instructions for variable content. HTML combined with a student-name expression.
Server-side rendering Producing the page content on the server before sending it to the client. The server returns HTML containing the greeting.
MVC Model–View–Controller: a separation of application data/rules, presentation and request coordination. Service/data objects, JSP and servlet respectively.
Model Application data and the rules or operations that act on it. A student object and student-management service.
View The presentation of application data to the user. A JSP page; it should not contain SQL or business rules.
Controller The component that handles a request, invokes application operations and selects a response or view. StudentServlet.
JSP directive An instruction to the JSP container about page processing or configuration. <%@ page ... %> or <%@ taglib ... %>.
Expression Language (EL) Expression syntax for reading values and evaluating expressions in a page. ${studentName} reads an attribute value.
Tag library A collection of reusable tags for view operations. Jakarta Tags, commonly called JSTL, provides conditional and output tags.
Scriptlet A Java code fragment embedded in a JSP using <% ... %>. A legacy technique avoided for application logic in this chapter.
Output escaping Converting characters with markup meaning into a representation suitable for the output context. Showing <b>Asha</b> as text rather than HTML.
Forward A server-side transfer of the current request to another resource. Passing the request from a servlet to a JSP.
Redirect A response instructing the client to request another URL. A new GET after a successful form submission.

An EL expression is not an output-escaping guarantee. The example uses c:out when displaying a user-supplied value in HTML text.

JSP processing lifecycle

A JSP follows a translation and execution process:

  1. The container translates the JSP into servlet source and compiles it, either in advance or when needed.
  2. The generated servlet is loaded and initialised; jspInit() is its JSP initialisation callback.
  3. For each request, the container invokes the generated _jspService() method to produce the response.
  4. Before the generated servlet is removed from service, its jspDestroy() callback supports cleanup.

Translation and compilation are not normally repeated for every request. A changed page may need to be translated again. Learners write the JSP template; the container generates _jspService() rather than requiring them to implement it.

Separation of responsibilities in the example

Keep three jobs separate: the Controller servlet handles the request, the Model supplies application data and rules, and the View JSP presents the result.

In this small greeting example, the servlet validates the name and passes it as a request attribute. In a larger application, the controller calls a service to obtain model objects. MVC describes these responsibilities; JSP is one way to implement the View.

JSP syntax and implicit objects

JSP supports several constructs. Understanding the older Java constructs helps when reading reference material, although this chapter keeps application logic in Java classes and uses EL and tags for the view.

Construct Syntax Purpose
Page directive <%@ page ... %> Page settings such as content type and encoding
Tag-library directive <%@ taglib ... %> Declare a tag prefix and library
Include directive <%@ include file="..." %> Include source content during translation
JSP expression <%= expression %> Evaluate Java and write the value to the output; not automatic HTML escaping
JSP declaration <%! ... %> Declare members of the generated servlet
Scriptlet <% ... %> Java statements embedded in request-processing code
EL expression ${studentName} Evaluate a value through Expression Language
Tag action <c:out value="${studentName}"/> Reusable view behaviour, here escaped text output

A JSP declaration creates a member of the generated servlet. A field declared this way may be shared by several requests, so do not use it to store the current user's data.

The two include forms work at different times. The include directive combines source files when the JSP is translated. The jsp:include action runs another resource while processing a request and inserts that resource's output.

JSP supplies implicit objects in its generated code:

Object Meaning
request Current HttpServletRequest
response Current HttpServletResponse
session Current HttpSession when session participation is enabled
application ServletContext shared by the web application
out JspWriter used to write response content
pageContext Access to page facilities and scoped attributes
config ServletConfig for the generated servlet
page Reference to the generated servlet instance
exception Available on an error page declared with isErrorPage="true"

Attribute scopes are page, request, session and application. EL can use explicit scope maps, such as ${requestScope.studentName}. The raw request parameter is available through ${param.name}; this is different from a server-created request attribute.

Servlet and JSP comparison

Both ultimately execute as Java servlet code on the server. A servlet is authored as a Java class and is commonly used to coordinate a request. A JSP is authored as a template and is commonly used to render a view. Java servlet source is compiled during the application build; JSP source is translated and compiled by the container, or precompiled during a build. A modified JSP can require recompilation: the container normally performs that work automatically. Neither technology makes business logic or security checks unnecessary.

MVC request flow at a glance

  1. 1. RequestThe browser submits the student form.
  2. 2. Controller and modelThe servlet validates input and obtains the data needed for the view.
  3. 3. JSP viewThe JSP renders HTML using the supplied attributes.

The response returns to the browser. The browser receives the generated content; it does not execute the JSP or access a Java request attribute directly.

Worked example: the JSP view

Save the following as src/main/webapp/WEB-INF/student.jsp. It is already included in the Servlet/JSP example.

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<!doctype html>
<html lang="en-GB"><head><meta charset="utf-8"><title>Student greeting</title></head>
<body><h1>Student greeting</h1>
<form action="${pageContext.request.contextPath}/student" method="post">
<label for="name">Name</label><input id="name" name="name" maxlength="80" required>
<button type="submit">Greet</button></form>
<c:if test="${not empty studentName}"><p>Hello, <c:out value="${studentName}"/>.</p></c:if>
</body></html>

Trace the name through the example: name="name" on the input creates the request parameter called name. The servlet validates it, then stores the result in the request attribute studentName. The JSP reads that attribute through ${studentName}.

Reading a value and displaying it safely are different steps. The c:out tag escapes HTML-sensitive characters when the value is placed in HTML text. Without suitable escaping, untrusted input can become markup or script. JavaScript and URL contexts need their own output handling; HTML-text escaping alone is not sufficient there.

Uniform Resource Identifier (URI) is a string that identifies a resource, such as a web endpoint.

The tag library uses the Jakarta Tags 3 URI jakarta.tags.core. The project bundles JSTL; Tomcat supplies JSP execution. The JSP is under WEB-INF so it cannot be requested directly by a browser; the servlet forwards to it. Avoid scriptlets such as <% ... %> for application logic.

Forward and redirect

Forward Redirect
Server transfers control internally Browser is asked to make a new request
Same request and attributes New request; ordinary request attributes are lost
URL normally stays unchanged Browser URL changes
Suitable for displaying a view Useful after a successful state-changing form

The greeting forwards after POST to keep the example small. For a database insert, Post/Redirect/Get is often preferable: perform the update, redirect to a GET URL and render the result there. Refresh then repeats the GET rather than the POST. A redirect does not undo a database change.

Trace and check

  1. GET /pblj-web/student reaches doGet().
  2. The servlet forwards to the JSP; the form is rendered.
  3. POST sends a name parameter to doPost().
  4. The servlet validates it and sets a request attribute.
  5. The JSP displays an escaped greeting.

Submit <b>Asha</b> and check that it appears as text rather than producing bold markup. Visit the GET URL again: the request-only greeting has not been permanently stored.

Keep the two example projects distinct

Web Application Archive (WAR) packages a Java web application for deployment to a compatible servlet container. JavaScript Object Notation (JSON) is a text format for exchanging values such as objects, arrays, strings, numbers and booleans. Java Archive (JAR) is a package of Java classes and related resources stored in one archive file.

The Servlet/JSP example is a WAR deployed to a Jakarta container. The later Spring Boot example uses a small JSON controller to exercise services and error handling. JSP is not supported in Boot executable JAR packaging; it needs appropriate WAR/container and view configuration. Copying this JSP into the Boot project alone is insufficient.

Summary

JSP expresses the View as a server-side template that becomes a servlet. MVC separates presentation, request coordination and application rules. A forward preserves the request; a redirect starts a new one. Display untrusted values with output handling appropriate to their context.

Practice

  1. Add a department field and display escaped output.
  2. Explain why request attributes disappear after a redirect.
  3. Draw a Post/Redirect/Get flow for creating a student record.

Quick check

Check your understanding

Does the browser execute a JSP? No. The server executes its generated servlet and sends the resulting page.

Further reading

Review questions

1. Does ${studentName} alone guarantee safe HTML output?

Answer: No. Reading a value and escaping it are separate operations. Use the appropriate escaping operation, such as c:out for HTML text.

2. After a redirect, is the previous request attribute automatically available?

Answer: No. The browser makes a new request. Preserve only necessary data through an explicitly chosen mechanism, rather than assuming request attributes survive.