0
# Java Servlet API
1
2
The Java Servlet API is a comprehensive framework for building web applications in Java. It provides a complete set of interfaces and classes for handling HTTP requests, managing sessions, implementing security, and building scalable web applications. The API consists of 77 components across 4 packages, offering both traditional synchronous and modern asynchronous processing capabilities.
3
4
## Package Information
5
6
**Maven Dependency:**
7
```xml
8
<dependency>
9
<groupId>javax.servlet</groupId>
10
<artifactId>javax.servlet-api</artifactId>
11
<version>4.0.1</version>
12
<scope>provided</scope>
13
</dependency>
14
```
15
16
**Java Version:** Requires Java 8 or higher
17
**Servlet Specification:** Based on Java EE 8 / Jakarta EE 8 specification
18
**Container Support:** Works with all major servlet containers (Tomcat, Jetty, GlassFish, WebLogic, etc.)
19
20
## Core Imports
21
22
```java { .api }
23
// Core servlet interfaces
24
import javax.servlet.Servlet;
25
import javax.servlet.ServletConfig;
26
import javax.servlet.ServletContext;
27
import javax.servlet.ServletRequest;
28
import javax.servlet.ServletResponse;
29
import javax.servlet.ServletException;
30
import javax.servlet.GenericServlet;
31
32
// HTTP-specific interfaces and classes
33
import javax.servlet.http.HttpServlet;
34
import javax.servlet.http.HttpServletRequest;
35
import javax.servlet.http.HttpServletResponse;
36
import javax.servlet.http.HttpSession;
37
import javax.servlet.http.Cookie;
38
39
// Filter interfaces
40
import javax.servlet.Filter;
41
import javax.servlet.FilterChain;
42
import javax.servlet.FilterConfig;
43
44
// Async processing
45
import javax.servlet.AsyncContext;
46
import javax.servlet.AsyncListener;
47
48
// Input/Output streams
49
import javax.servlet.ServletInputStream;
50
import javax.servlet.ServletOutputStream;
51
52
// Annotations (Servlet 3.0+)
53
import javax.servlet.annotation.WebServlet;
54
import javax.servlet.annotation.WebFilter;
55
import javax.servlet.annotation.WebListener;
56
import javax.servlet.annotation.WebInitParam;
57
import javax.servlet.annotation.MultipartConfig;
58
59
// Event listeners
60
import javax.servlet.ServletContextListener;
61
import javax.servlet.ServletRequestListener;
62
import javax.servlet.http.HttpSessionListener;
63
```
64
65
## Basic Usage
66
67
### Simple HTTP Servlet
68
69
```java { .api }
70
import javax.servlet.http.HttpServlet;
71
import javax.servlet.http.HttpServletRequest;
72
import javax.servlet.http.HttpServletResponse;
73
import java.io.IOException;
74
75
/**
76
* Basic servlet handling GET and POST requests
77
*/
78
@WebServlet(name = "HelloServlet", urlPatterns = {"/hello", "/greeting"})
79
public class HelloServlet extends HttpServlet {
80
81
@Override
82
public void doGet(HttpServletRequest request, HttpServletResponse response)
83
throws ServletException, IOException {
84
85
// Set response content type
86
response.setContentType("text/html;charset=UTF-8");
87
88
// Get request parameters
89
String name = request.getParameter("name");
90
if (name == null) {
91
name = "World";
92
}
93
94
// Write response
95
try (PrintWriter out = response.getWriter()) {
96
out.println("<html>");
97
out.println("<head><title>Hello Servlet</title></head>");
98
out.println("<body>");
99
out.println("<h1>Hello " + name + "!</h1>");
100
out.println("</body></html>");
101
}
102
}
103
104
@Override
105
public void doPost(HttpServletRequest request, HttpServletResponse response)
106
throws ServletException, IOException {
107
doGet(request, response);
108
}
109
}
110
```
111
112
### Basic Filter
113
114
```java { .api }
115
import javax.servlet.*;
116
import javax.servlet.http.HttpServletRequest;
117
import java.io.IOException;
118
119
/**
120
* Basic request logging filter
121
*/
122
@WebFilter(filterName = "LoggingFilter", urlPatterns = {"/*"})
123
public class LoggingFilter implements Filter {
124
125
@Override
126
public void init(FilterConfig filterConfig) throws ServletException {
127
// Initialize filter
128
}
129
130
@Override
131
public void doFilter(ServletRequest request, ServletResponse response,
132
FilterChain chain) throws IOException, ServletException {
133
134
HttpServletRequest httpRequest = (HttpServletRequest) request;
135
136
// Log the request
137
System.out.println("Request: " + httpRequest.getMethod() +
138
" " + httpRequest.getRequestURL());
139
140
// Continue the chain
141
chain.doFilter(request, response);
142
143
// Log after processing
144
System.out.println("Response sent for: " + httpRequest.getRequestURL());
145
}
146
147
@Override
148
public void destroy() {
149
// Clean up resources
150
}
151
}
152
```
153
154
## Architecture
155
156
The Java Servlet API is organized into four main packages:
157
158
### Package Structure
159
160
1. **javax.servlet** (41 components) - Core servlet functionality
161
- Base servlet and filter interfaces
162
- Request/response abstractions
163
- Context and configuration management
164
- Asynchronous processing support
165
166
2. **javax.servlet.http** (26 components) - HTTP-specific extensions
167
- HTTP servlet implementations
168
- Session management
169
- Cookie handling
170
- HTTP/2 server push support
171
172
3. **javax.servlet.annotation** (7 components) - Declarative configuration
173
- Annotation-based servlet configuration
174
- Security constraint annotations
175
- Initialization parameter annotations
176
177
4. **javax.servlet.descriptor** (3 components) - Deployment descriptor access
178
- Programmatic access to web.xml configuration
179
- JSP configuration descriptors
180
181
### Core Components
182
183
```java { .api }
184
/**
185
* Core servlet lifecycle interface - all servlets must implement this
186
*/
187
public interface Servlet {
188
void init(ServletConfig config) throws ServletException;
189
ServletConfig getServletConfig();
190
void service(ServletRequest req, ServletResponse res) throws ServletException, IOException;
191
String getServletInfo();
192
void destroy();
193
}
194
195
/**
196
* HTTP-specific servlet base class
197
*/
198
public abstract class HttpServlet extends GenericServlet {
199
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
200
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
201
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
202
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
203
protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
204
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
205
protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
206
}
207
208
/**
209
* Filter interface for request/response processing
210
*/
211
public interface Filter {
212
void init(FilterConfig filterConfig) throws ServletException;
213
void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
214
throws IOException, ServletException;
215
void destroy();
216
}
217
```
218
219
## Core Servlet Lifecycle and Configuration
220
221
**→** [Servlet Lifecycle and Configuration](./servlet-lifecycle.md) - Complete coverage of servlet initialization, configuration, context management, and deployment patterns.
222
223
Key APIs covered:
224
- `Servlet`, `ServletConfig`, `ServletContext` interfaces
225
- `GenericServlet` and lifecycle management
226
- Context attributes and initialization parameters
227
- `ServletContainerInitializer` for programmatic configuration
228
- Registration APIs for dynamic servlet/filter setup
229
230
```java { .api }
231
// Basic servlet lifecycle
232
public class MyServlet extends HttpServlet {
233
@Override
234
public void init(ServletConfig config) throws ServletException {
235
super.init(config);
236
// Servlet initialization logic
237
ServletContext context = getServletContext();
238
String initParam = getInitParameter("configParam");
239
}
240
}
241
```
242
243
## HTTP Request and Response Processing
244
245
**→** [HTTP Request and Response Processing](./http-processing.md) - Comprehensive HTTP handling including request parsing, response generation, headers, parameters, and advanced features.
246
247
Key APIs covered:
248
- `HttpServletRequest` and `HttpServletResponse` interfaces
249
- HTTP method handling (`doGet`, `doPost`, etc.)
250
- Request parameters, headers, and attributes
251
- Response status codes, headers, and output streams
252
- Multipart request processing and file uploads
253
- HTTP/2 server push with `PushBuilder`
254
255
```java { .api }
256
// HTTP request/response processing
257
@Override
258
protected void doPost(HttpServletRequest request, HttpServletResponse response)
259
throws ServletException, IOException {
260
261
// Process request parameters
262
String param = request.getParameter("data");
263
Part filePart = request.getPart("file");
264
265
// Set response
266
response.setStatus(HttpServletResponse.SC_OK);
267
response.setContentType("application/json");
268
response.getWriter().write("{\"status\":\"success\"}");
269
}
270
```
271
272
## Session Management and Cookies
273
274
**→** [Session Management and Cookies](./session-cookies.md) - Complete session lifecycle, cookie management, session tracking modes, and security considerations.
275
276
Key APIs covered:
277
- `HttpSession` interface and session lifecycle
278
- `Cookie` class for client-side state management
279
- Session tracking modes (cookies, URL rewriting, SSL)
280
- `SessionCookieConfig` for session cookie configuration
281
- Session security and timeout management
282
283
```java { .api }
284
// Session and cookie management
285
HttpSession session = request.getSession();
286
session.setAttribute("user", currentUser);
287
288
Cookie userCookie = new Cookie("username", user.getName());
289
userCookie.setMaxAge(3600);
290
userCookie.setHttpOnly(true);
291
response.addCookie(userCookie);
292
```
293
294
## Asynchronous Processing and I/O
295
296
**→** [Asynchronous Processing and I/O](./async-processing.md) - Modern async servlet processing, non-blocking I/O, and scalable request handling patterns.
297
298
Key APIs covered:
299
- `AsyncContext` for asynchronous request processing
300
- `ReadListener` and `WriteListener` for non-blocking I/O
301
- `ServletInputStream` and `ServletOutputStream` async methods
302
- `AsyncListener` for async event handling
303
- Thread management and async dispatch
304
305
```java { .api }
306
// Asynchronous processing
307
@WebServlet(asyncSupported = true)
308
public class AsyncServlet extends HttpServlet {
309
@Override
310
protected void doGet(HttpServletRequest request, HttpServletResponse response)
311
throws ServletException, IOException {
312
313
AsyncContext asyncContext = request.startAsync();
314
asyncContext.setTimeout(30000);
315
316
asyncContext.start(() -> {
317
// Long-running operation
318
processRequestAsync(asyncContext);
319
});
320
}
321
}
322
```
323
324
## Security and Filtering
325
326
**→** [Security and Filtering](./security-filtering.md) - Comprehensive security framework including authentication, authorization, filters, and security constraints.
327
328
Key APIs covered:
329
- Security constraint annotations (`@ServletSecurity`, `@HttpConstraint`)
330
- Filter chain processing and security filters
331
- Authentication and role-based authorization
332
- Transport security and HTTPS enforcement
333
- `RequestDispatcher` for forwarding and including
334
335
```java { .api }
336
// Security configuration
337
@ServletSecurity(
338
@HttpConstraint(rolesAllowed = {"admin", "user"}),
339
httpMethodConstraints = {
340
@HttpMethodConstraint(value = "DELETE", rolesAllowed = {"admin"})
341
}
342
)
343
public class SecureServlet extends HttpServlet {
344
// Servlet implementation
345
}
346
```
347
348
## Listeners and Events
349
350
**→** [Listeners and Events](./listeners-events.md) - Complete event handling system for application lifecycle, session events, and attribute changes.
351
352
Key APIs covered:
353
- Context lifecycle listeners (`ServletContextListener`)
354
- Session lifecycle listeners (`HttpSessionListener`, `HttpSessionActivationListener`)
355
- Attribute change listeners for contexts, sessions, and requests
356
- Event objects and listener registration
357
- Application startup and shutdown handling
358
359
```java { .api }
360
// Event listeners
361
@WebListener
362
public class AppLifecycleListener implements ServletContextListener {
363
@Override
364
public void contextInitialized(ServletContextEvent sce) {
365
// Application startup logic
366
ServletContext context = sce.getServletContext();
367
initializeApplication(context);
368
}
369
}
370
```
371
372
## Component Summary
373
374
The Java Servlet API provides 77 components organized by functionality:
375
376
- **Interfaces**: 44 (57%) - Core contracts and extension points
377
- **Classes**: 26 (34%) - Base implementations and utilities
378
- **Enums**: 4 (5%) - Type-safe constants and options
379
- **Annotations**: 9 (12%) - Declarative configuration support
380
381
### Key Features
382
383
- **Complete HTTP Support**: Full HTTP/1.1 and HTTP/2 compatibility
384
- **Asynchronous Processing**: Non-blocking I/O and async request handling
385
- **Security Framework**: Comprehensive authentication and authorization
386
- **Session Management**: Robust session lifecycle and state management
387
- **Event-Driven Architecture**: Extensive listener interfaces for lifecycle events
388
- **Filter Chain**: Powerful request/response processing pipeline
389
- **Annotation Configuration**: Modern declarative configuration alongside XML
390
- **Multipart Processing**: Built-in support for file uploads and form data
391
- **Container Integration**: Works with all major Java web containers
392
393
The API supports both traditional servlet patterns and modern async/reactive approaches, making it suitable for a wide range of web application architectures from simple web services to complex enterprise applications.