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.
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:
- Define a servlet, servlet container, HTTP request and HTTP response.
- Identify the parts of a web address and explain servlet mapping.
- Describe initialisation, request processing and destruction in the servlet lifecycle.
- Distinguish request parameters, attributes and session state.
- 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
- BrowserRequests the resource
- Web serverFinds an existing file
- 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.
- BrowserRequests grades
- Servlet and serviceValidate and process the request
- 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.
- ConstructCreate the servlet instance.
- InitialiseCall init() once for this instance.
- Process requestsCall service() for each request.
- 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:
doGet()forwards to the JSP so the browser can display the form.doPost()sets the character encoding before reading the submittedname.- Invalid input returns HTTP 400 and stops processing. Valid input becomes the
studentNamerequest attribute. - 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.
- Extract the ZIP and open a terminal in the folder containing
pom.xml. - Run
mvn packageto buildtarget/pblj-web.war. - Copy that WAR into Tomcat 10.1's
webappsdirectory and start Tomcat. - Open
http://localhost:8080/pblj-web/studentin a browser. - Enter
Ashaand submit the form. The page should displayHello, 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
- Add a department parameter and pass it to the JSP.
- Compare request, session and application scope.
- 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.