0
# Jakarta Servlet API
1
2
Complete implementation of Jakarta Servlet 6.0 specification providing the foundation for Java web application development. This includes servlet lifecycle management, request/response handling, filters, listeners, sessions, async processing, security constraints, and multipart file uploads.
3
4
## Capabilities
5
6
### Core Servlet Interfaces
7
8
The fundamental servlet API for handling HTTP requests and responses.
9
10
```java { .api }
11
// Base servlet interface
12
public interface Servlet {
13
void init(ServletConfig config) throws ServletException;
14
void service(ServletRequest req, ServletResponse res) throws ServletException, IOException;
15
void destroy();
16
ServletConfig getServletConfig();
17
String getServletInfo();
18
}
19
20
// Servlet configuration
21
public interface ServletConfig {
22
String getServletName();
23
ServletContext getServletContext();
24
String getInitParameter(String name);
25
Enumeration<String> getInitParameterNames();
26
}
27
28
// Generic servlet base class
29
public abstract class GenericServlet implements Servlet, ServletConfig {
30
public GenericServlet();
31
public void destroy();
32
public String getInitParameter(String name);
33
public Enumeration<String> getInitParameterNames();
34
public ServletConfig getServletConfig();
35
public ServletContext getServletContext();
36
public String getServletInfo();
37
public void init(ServletConfig config) throws ServletException;
38
public void init() throws ServletException;
39
public void log(String message);
40
public void log(String message, Throwable t);
41
public abstract void service(ServletRequest req, ServletResponse res)
42
throws ServletException, IOException;
43
public String getServletName();
44
}
45
```
46
47
### HTTP Servlet
48
49
HTTP-specific servlet implementation extending GenericServlet for web applications.
50
51
```java { .api }
52
public abstract class HttpServlet extends GenericServlet {
53
public static final String LEGACY_DO_HEAD = "jakarta.servlet.http.legacyDoHead";
54
55
public HttpServlet();
56
57
// HTTP method handlers
58
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
59
throws ServletException, IOException;
60
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
61
throws ServletException, IOException;
62
protected void doPut(HttpServletRequest req, HttpServletResponse resp)
63
throws ServletException, IOException;
64
protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
65
throws ServletException, IOException;
66
protected void doHead(HttpServletRequest req, HttpServletResponse resp)
67
throws ServletException, IOException;
68
protected void doOptions(HttpServletRequest req, HttpServletResponse resp)
69
throws ServletException, IOException;
70
protected void doTrace(HttpServletRequest req, HttpServletResponse resp)
71
throws ServletException, IOException;
72
73
protected long getLastModified(HttpServletRequest req);
74
protected void service(HttpServletRequest req, HttpServletResponse resp)
75
throws ServletException, IOException;
76
public void service(ServletRequest req, ServletResponse res)
77
throws ServletException, IOException;
78
}
79
```
80
81
### Servlet Request and Response
82
83
Interfaces for accessing request data and generating responses.
84
85
```java { .api }
86
// Generic servlet request
87
public interface ServletRequest {
88
Object getAttribute(String name);
89
Enumeration<String> getAttributeNames();
90
String getCharacterEncoding();
91
void setCharacterEncoding(String encoding) throws UnsupportedEncodingException;
92
int getContentLength();
93
long getContentLengthLong();
94
String getContentType();
95
ServletInputStream getInputStream() throws IOException;
96
String getParameter(String name);
97
Enumeration<String> getParameterNames();
98
String[] getParameterValues(String name);
99
Map<String,String[]> getParameterMap();
100
String getProtocol();
101
String getScheme();
102
String getServerName();
103
int getServerPort();
104
BufferedReader getReader() throws IOException;
105
String getRemoteAddr();
106
String getRemoteHost();
107
void setAttribute(String name, Object o);
108
void removeAttribute(String name);
109
Locale getLocale();
110
Enumeration<Locale> getLocales();
111
boolean isSecure();
112
RequestDispatcher getRequestDispatcher(String path);
113
int getRemotePort();
114
String getLocalName();
115
String getLocalAddr();
116
int getLocalPort();
117
ServletContext getServletContext();
118
AsyncContext startAsync() throws IllegalStateException;
119
AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse)
120
throws IllegalStateException;
121
boolean isAsyncStarted();
122
boolean isAsyncSupported();
123
AsyncContext getAsyncContext();
124
DispatcherType getDispatcherType();
125
String getRequestId();
126
String getProtocolRequestId();
127
ServletConnection getServletConnection();
128
}
129
130
// Generic servlet response
131
public interface ServletResponse {
132
String getCharacterEncoding();
133
String getContentType();
134
ServletOutputStream getOutputStream() throws IOException;
135
PrintWriter getWriter() throws IOException;
136
void setCharacterEncoding(String charset);
137
void setContentLength(int len);
138
void setContentLengthLong(long length);
139
void setContentType(String type);
140
void setBufferSize(int size);
141
int getBufferSize();
142
void flushBuffer() throws IOException;
143
void resetBuffer();
144
boolean isCommitted();
145
void reset();
146
void setLocale(Locale loc);
147
Locale getLocale();
148
}
149
```
150
151
### HTTP Request and Response
152
153
HTTP-specific extensions with cookies, headers, sessions, and redirects.
154
155
```java { .api }
156
public interface HttpServletRequest extends ServletRequest {
157
// Authentication
158
String getAuthType();
159
String getRemoteUser();
160
boolean isUserInRole(String role);
161
Principal getUserPrincipal();
162
boolean authenticate(HttpServletResponse response) throws IOException, ServletException;
163
void login(String username, String password) throws ServletException;
164
void logout() throws ServletException;
165
166
// Cookies
167
Cookie[] getCookies();
168
169
// Headers
170
long getDateHeader(String name);
171
String getHeader(String name);
172
Enumeration<String> getHeaders(String name);
173
Enumeration<String> getHeaderNames();
174
int getIntHeader(String name);
175
176
// HTTP method and path
177
String getMethod();
178
String getPathInfo();
179
String getPathTranslated();
180
String getContextPath();
181
String getQueryString();
182
String getRequestURI();
183
StringBuffer getRequestURL();
184
String getServletPath();
185
HttpServletMapping getHttpServletMapping();
186
187
// Sessions
188
HttpSession getSession(boolean create);
189
HttpSession getSession();
190
String getRequestedSessionId();
191
boolean isRequestedSessionIdValid();
192
boolean isRequestedSessionIdFromCookie();
193
boolean isRequestedSessionIdFromURL();
194
String changeSessionId();
195
196
// Multipart
197
Collection<Part> getParts() throws IOException, ServletException;
198
Part getPart(String name) throws IOException, ServletException;
199
200
// HTTP/2 features
201
PushBuilder newPushBuilder();
202
Map<String,String> getTrailerFields();
203
boolean isTrailerFieldsReady();
204
205
// Protocol upgrade
206
<T extends HttpUpgradeHandler> T upgrade(Class<T> handlerClass)
207
throws IOException, ServletException;
208
}
209
210
public interface HttpServletResponse extends ServletResponse {
211
// Status codes (constants omitted for brevity)
212
int SC_CONTINUE = 100;
213
int SC_OK = 200;
214
int SC_CREATED = 201;
215
int SC_BAD_REQUEST = 400;
216
int SC_UNAUTHORIZED = 401;
217
int SC_FORBIDDEN = 403;
218
int SC_NOT_FOUND = 404;
219
int SC_INTERNAL_SERVER_ERROR = 500;
220
// ... more status code constants
221
222
// Cookies
223
void addCookie(Cookie cookie);
224
225
// Headers
226
boolean containsHeader(String name);
227
String encodeURL(String url);
228
String encodeRedirectURL(String url);
229
void sendError(int sc, String msg) throws IOException;
230
void sendError(int sc) throws IOException;
231
void sendRedirect(String location) throws IOException;
232
void setDateHeader(String name, long date);
233
void addDateHeader(String name, long date);
234
void setHeader(String name, String value);
235
void addHeader(String name, String value);
236
void setIntHeader(String name, int value);
237
void addIntHeader(String name, int value);
238
void setStatus(int sc);
239
int getStatus();
240
String getHeader(String name);
241
Collection<String> getHeaders(String name);
242
Collection<String> getHeaderNames();
243
244
// HTTP/2 trailers
245
void setTrailerFields(Supplier<Map<String,String>> supplier);
246
Supplier<Map<String,String>> getTrailerFields();
247
248
// Early hints (HTTP 103)
249
void sendEarlyHints();
250
}
251
```
252
253
### Request and Response Wrapper Classes
254
255
Convenience classes for implementing the decorator pattern with servlet requests and responses. These wrapper classes delegate all method calls to the wrapped object, allowing developers to override only specific methods.
256
257
```java { .api }
258
/**
259
* Wrapper for ServletRequest that delegates all method calls to the wrapped request.
260
* Extend this class and override specific methods to customize request behavior.
261
*/
262
public class ServletRequestWrapper implements ServletRequest {
263
public ServletRequestWrapper(ServletRequest request);
264
public ServletRequest getRequest();
265
public void setRequest(ServletRequest request);
266
267
// All ServletRequest methods delegate to wrapped request
268
@Override
269
public Object getAttribute(String name);
270
@Override
271
public Enumeration<String> getAttributeNames();
272
@Override
273
public String getCharacterEncoding();
274
@Override
275
public void setCharacterEncoding(String env) throws UnsupportedEncodingException;
276
@Override
277
public int getContentLength();
278
@Override
279
public long getContentLengthLong();
280
@Override
281
public String getContentType();
282
@Override
283
public ServletInputStream getInputStream() throws IOException;
284
@Override
285
public String getParameter(String name);
286
@Override
287
public Map<String,String[]> getParameterMap();
288
@Override
289
public Enumeration<String> getParameterNames();
290
@Override
291
public String[] getParameterValues(String name);
292
@Override
293
public String getProtocol();
294
@Override
295
public String getScheme();
296
@Override
297
public String getServerName();
298
@Override
299
public int getServerPort();
300
@Override
301
public BufferedReader getReader() throws IOException;
302
@Override
303
public String getRemoteAddr();
304
@Override
305
public String getRemoteHost();
306
@Override
307
public void setAttribute(String name, Object o);
308
@Override
309
public void removeAttribute(String name);
310
@Override
311
public Locale getLocale();
312
@Override
313
public Enumeration<Locale> getLocales();
314
@Override
315
public boolean isSecure();
316
@Override
317
public RequestDispatcher getRequestDispatcher(String path);
318
@Override
319
public int getRemotePort();
320
@Override
321
public String getLocalName();
322
@Override
323
public String getLocalAddr();
324
@Override
325
public int getLocalPort();
326
@Override
327
public ServletContext getServletContext();
328
@Override
329
public AsyncContext startAsync() throws IllegalStateException;
330
@Override
331
public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse)
332
throws IllegalStateException;
333
@Override
334
public boolean isAsyncStarted();
335
@Override
336
public boolean isAsyncSupported();
337
@Override
338
public AsyncContext getAsyncContext();
339
@Override
340
public DispatcherType getDispatcherType();
341
@Override
342
public String getRequestId();
343
@Override
344
public String getProtocolRequestId();
345
@Override
346
public ServletConnection getServletConnection();
347
}
348
349
/**
350
* Wrapper for HttpServletRequest that delegates all method calls to the wrapped request.
351
* Extends ServletRequestWrapper and adds HTTP-specific delegation.
352
*/
353
public class HttpServletRequestWrapper extends ServletRequestWrapper implements HttpServletRequest {
354
public HttpServletRequestWrapper(HttpServletRequest request);
355
356
// All HttpServletRequest methods delegate to wrapped HTTP request
357
@Override
358
public String getAuthType();
359
@Override
360
public Cookie[] getCookies();
361
@Override
362
public long getDateHeader(String name);
363
@Override
364
public String getHeader(String name);
365
@Override
366
public Enumeration<String> getHeaders(String name);
367
@Override
368
public Enumeration<String> getHeaderNames();
369
@Override
370
public int getIntHeader(String name);
371
@Override
372
public HttpServletMapping getHttpServletMapping();
373
@Override
374
public String getMethod();
375
@Override
376
public String getPathInfo();
377
@Override
378
public String getPathTranslated();
379
@Override
380
public String getContextPath();
381
@Override
382
public String getQueryString();
383
@Override
384
public String getRemoteUser();
385
@Override
386
public boolean isUserInRole(String role);
387
@Override
388
public Principal getUserPrincipal();
389
@Override
390
public String getRequestedSessionId();
391
@Override
392
public String getRequestURI();
393
@Override
394
public StringBuffer getRequestURL();
395
@Override
396
public String getServletPath();
397
@Override
398
public HttpSession getSession(boolean create);
399
@Override
400
public HttpSession getSession();
401
@Override
402
public String changeSessionId();
403
@Override
404
public boolean isRequestedSessionIdValid();
405
@Override
406
public boolean isRequestedSessionIdFromCookie();
407
@Override
408
public boolean isRequestedSessionIdFromURL();
409
@Override
410
public boolean authenticate(HttpServletResponse response) throws IOException, ServletException;
411
@Override
412
public void login(String username, String password) throws ServletException;
413
@Override
414
public void logout() throws ServletException;
415
@Override
416
public Collection<Part> getParts() throws IOException, ServletException;
417
@Override
418
public Part getPart(String name) throws IOException, ServletException;
419
@Override
420
public <T extends HttpUpgradeHandler> T upgrade(Class<T> httpUpgradeHandlerClass)
421
throws IOException, ServletException;
422
@Override
423
public PushBuilder newPushBuilder();
424
@Override
425
public Map<String,String> getTrailerFields();
426
@Override
427
public boolean isTrailerFieldsReady();
428
}
429
430
/**
431
* Wrapper for ServletResponse that delegates all method calls to the wrapped response.
432
* Extend this class and override specific methods to customize response behavior.
433
*/
434
public class ServletResponseWrapper implements ServletResponse {
435
public ServletResponseWrapper(ServletResponse response);
436
public ServletResponse getResponse();
437
public void setResponse(ServletResponse response);
438
439
// All ServletResponse methods delegate to wrapped response
440
@Override
441
public String getCharacterEncoding();
442
@Override
443
public String getContentType();
444
@Override
445
public ServletOutputStream getOutputStream() throws IOException;
446
@Override
447
public PrintWriter getWriter() throws IOException;
448
@Override
449
public void setCharacterEncoding(String charset);
450
@Override
451
public void setContentLength(int len);
452
@Override
453
public void setContentLengthLong(long len);
454
@Override
455
public void setContentType(String type);
456
@Override
457
public void setBufferSize(int size);
458
@Override
459
public int getBufferSize();
460
@Override
461
public void flushBuffer() throws IOException;
462
@Override
463
public void resetBuffer();
464
@Override
465
public boolean isCommitted();
466
@Override
467
public void reset();
468
@Override
469
public void setLocale(Locale loc);
470
@Override
471
public Locale getLocale();
472
}
473
474
/**
475
* Wrapper for HttpServletResponse that delegates all method calls to the wrapped response.
476
* Extends ServletResponseWrapper and adds HTTP-specific delegation.
477
*/
478
public class HttpServletResponseWrapper extends ServletResponseWrapper implements HttpServletResponse {
479
public HttpServletResponseWrapper(HttpServletResponse response);
480
481
// All HttpServletResponse methods delegate to wrapped HTTP response
482
@Override
483
public void addCookie(Cookie cookie);
484
@Override
485
public boolean containsHeader(String name);
486
@Override
487
public String encodeURL(String url);
488
@Override
489
public String encodeRedirectURL(String url);
490
@Override
491
public void sendError(int sc, String msg) throws IOException;
492
@Override
493
public void sendError(int sc) throws IOException;
494
@Override
495
public void sendRedirect(String location) throws IOException;
496
@Override
497
public void setDateHeader(String name, long date);
498
@Override
499
public void addDateHeader(String name, long date);
500
@Override
501
public void setHeader(String name, String value);
502
@Override
503
public void addHeader(String name, String value);
504
@Override
505
public void setIntHeader(String name, int value);
506
@Override
507
public void addIntHeader(String name, int value);
508
@Override
509
public void setStatus(int sc);
510
@Override
511
public int getStatus();
512
@Override
513
public String getHeader(String name);
514
@Override
515
public Collection<String> getHeaders(String name);
516
@Override
517
public Collection<String> getHeaderNames();
518
@Override
519
public void setTrailerFields(Supplier<Map<String,String>> supplier);
520
@Override
521
public Supplier<Map<String,String>> getTrailerFields();
522
@Override
523
public void sendEarlyHints();
524
}
525
```
526
527
**Usage Example:**
528
529
```java
530
public class LoggingRequestWrapper extends HttpServletRequestWrapper {
531
private static final Logger logger = Logger.getLogger(LoggingRequestWrapper.class.getName());
532
533
public LoggingRequestWrapper(HttpServletRequest request) {
534
super(request);
535
}
536
537
@Override
538
public String getParameter(String name) {
539
String value = super.getParameter(name);
540
logger.info("Parameter '" + name + "' = '" + value + "'");
541
return value;
542
}
543
}
544
545
// In a filter:
546
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
547
throws IOException, ServletException {
548
HttpServletRequest httpRequest = (HttpServletRequest) request;
549
LoggingRequestWrapper wrapper = new LoggingRequestWrapper(httpRequest);
550
chain.doFilter(wrapper, response);
551
}
552
```
553
554
### Servlet Context
555
556
Web application context providing access to resources, configuration, and container services.
557
558
```java { .api }
559
public interface ServletContext {
560
// Context information
561
String getContextPath();
562
int getMajorVersion();
563
int getMinorVersion();
564
int getEffectiveMajorVersion();
565
int getEffectiveMinorVersion();
566
String getMimeType(String file);
567
Set<String> getResourcePaths(String path);
568
URL getResource(String path) throws MalformedURLException;
569
InputStream getResourceAsStream(String path);
570
RequestDispatcher getRequestDispatcher(String path);
571
RequestDispatcher getNamedDispatcher(String name);
572
String getRealPath(String path);
573
String getServerInfo();
574
String getServletContextName();
575
576
// Initialization parameters
577
String getInitParameter(String name);
578
Enumeration<String> getInitParameterNames();
579
boolean setInitParameter(String name, String value);
580
581
// Attributes
582
Object getAttribute(String name);
583
Enumeration<String> getAttributeNames();
584
void setAttribute(String name, Object object);
585
void removeAttribute(String name);
586
587
// Logging
588
void log(String msg);
589
void log(String message, Throwable throwable);
590
591
// Dynamic registration
592
ServletRegistration.Dynamic addServlet(String servletName, String className);
593
ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet);
594
ServletRegistration.Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass);
595
<T extends Servlet> T createServlet(Class<T> clazz) throws ServletException;
596
ServletRegistration getServletRegistration(String servletName);
597
Map<String,? extends ServletRegistration> getServletRegistrations();
598
599
FilterRegistration.Dynamic addFilter(String filterName, String className);
600
FilterRegistration.Dynamic addFilter(String filterName, Filter filter);
601
FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass);
602
<T extends Filter> T createFilter(Class<T> clazz) throws ServletException;
603
FilterRegistration getFilterRegistration(String filterName);
604
Map<String,? extends FilterRegistration> getFilterRegistrations();
605
606
void addListener(String className);
607
<T extends EventListener> void addListener(T t);
608
void addListener(Class<? extends EventListener> listenerClass);
609
<T extends EventListener> T createListener(Class<T> clazz) throws ServletException;
610
611
// Session configuration
612
SessionCookieConfig getSessionCookieConfig();
613
void setSessionTrackingModes(Set<SessionTrackingMode> sessionTrackingModes);
614
Set<SessionTrackingMode> getDefaultSessionTrackingModes();
615
Set<SessionTrackingMode> getEffectiveSessionTrackingModes();
616
617
// Security
618
void declareRoles(String... roleNames);
619
620
// Virtual server name
621
String getVirtualServerName();
622
623
// Session timeout
624
int getSessionTimeout();
625
void setSessionTimeout(int sessionTimeout);
626
627
// Request/response character encoding
628
String getRequestCharacterEncoding();
629
void setRequestCharacterEncoding(String encoding);
630
String getResponseCharacterEncoding();
631
void setResponseCharacterEncoding(String encoding);
632
633
// Additional context methods
634
ServletContext getContext(String uripath);
635
ClassLoader getClassLoader();
636
JspConfigDescriptor getJspConfigDescriptor();
637
ServletRegistration.Dynamic addJspFile(String jspName, String jspFile);
638
}
639
```
640
641
### Sessions
642
643
HTTP session management for maintaining user state across requests.
644
645
```java { .api }
646
public interface HttpSession {
647
long getCreationTime();
648
String getId();
649
long getLastAccessedTime();
650
ServletContext getServletContext();
651
void setMaxInactiveInterval(int interval);
652
int getMaxInactiveInterval();
653
Object getAttribute(String name);
654
Enumeration<String> getAttributeNames();
655
void setAttribute(String name, Object value);
656
void removeAttribute(String name);
657
void invalidate();
658
boolean isNew();
659
}
660
661
public interface SessionCookieConfig {
662
void setName(String name);
663
String getName();
664
void setDomain(String domain);
665
String getDomain();
666
void setPath(String path);
667
String getPath();
668
void setComment(String comment);
669
String getComment();
670
void setHttpOnly(boolean httpOnly);
671
boolean isHttpOnly();
672
void setSecure(boolean secure);
673
boolean isSecure();
674
void setMaxAge(int MaxAge);
675
int getMaxAge();
676
void setAttribute(String name, String value);
677
String getAttribute(String name);
678
Map<String,String> getAttributes();
679
}
680
681
public enum SessionTrackingMode {
682
COOKIE,
683
URL,
684
SSL
685
}
686
```
687
688
### Filters
689
690
Request/response filtering for cross-cutting concerns.
691
692
```java { .api }
693
public interface Filter {
694
default void init(FilterConfig filterConfig) throws ServletException {}
695
void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
696
throws IOException, ServletException;
697
default void destroy() {}
698
}
699
700
public interface FilterConfig {
701
String getFilterName();
702
ServletContext getServletContext();
703
String getInitParameter(String name);
704
Enumeration<String> getInitParameterNames();
705
}
706
707
public interface FilterChain {
708
void doFilter(ServletRequest request, ServletResponse response)
709
throws IOException, ServletException;
710
}
711
712
public abstract class GenericFilter implements Filter, FilterConfig {
713
public String getInitParameter(String name);
714
public Enumeration<String> getInitParameterNames();
715
public FilterConfig getFilterConfig();
716
public ServletContext getServletContext();
717
public void init(FilterConfig filterConfig) throws ServletException;
718
public void init() throws ServletException;
719
public String getFilterName();
720
}
721
722
public abstract class HttpFilter extends GenericFilter {
723
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
724
throws IOException, ServletException;
725
protected void doFilter(HttpServletRequest request, HttpServletResponse response,
726
FilterChain chain) throws IOException, ServletException;
727
}
728
```
729
730
### Listeners
731
732
Event listeners for servlet lifecycle, context, session, and request events.
733
734
```java { .api }
735
// Context listeners
736
public interface ServletContextListener extends EventListener {
737
default void contextInitialized(ServletContextEvent sce) {}
738
default void contextDestroyed(ServletContextEvent sce) {}
739
}
740
741
public interface ServletContextAttributeListener extends EventListener {
742
default void attributeAdded(ServletContextAttributeEvent event) {}
743
default void attributeRemoved(ServletContextAttributeEvent event) {}
744
default void attributeReplaced(ServletContextAttributeEvent event) {}
745
}
746
747
// Session listeners
748
public interface HttpSessionListener extends EventListener {
749
default void sessionCreated(HttpSessionEvent se) {}
750
default void sessionDestroyed(HttpSessionEvent se) {}
751
}
752
753
public interface HttpSessionAttributeListener extends EventListener {
754
default void attributeAdded(HttpSessionBindingEvent event) {}
755
default void attributeRemoved(HttpSessionBindingEvent event) {}
756
default void attributeReplaced(HttpSessionBindingEvent event) {}
757
}
758
759
public interface HttpSessionIdListener extends EventListener {
760
void sessionIdChanged(HttpSessionEvent event, String oldSessionId);
761
}
762
763
public interface HttpSessionActivationListener extends EventListener {
764
default void sessionWillPassivate(HttpSessionEvent se) {}
765
default void sessionDidActivate(HttpSessionEvent se) {}
766
}
767
768
public interface HttpSessionBindingListener extends EventListener {
769
default void valueBound(HttpSessionBindingEvent event) {}
770
default void valueUnbound(HttpSessionBindingEvent event) {}
771
}
772
773
// Request listeners
774
public interface ServletRequestListener extends EventListener {
775
default void requestInitialized(ServletRequestEvent sre) {}
776
default void requestDestroyed(ServletRequestEvent sre) {}
777
}
778
779
public interface ServletRequestAttributeListener extends EventListener {
780
default void attributeAdded(ServletRequestAttributeEvent srae) {}
781
default void attributeRemoved(ServletRequestAttributeEvent srae) {}
782
default void attributeReplaced(ServletRequestAttributeEvent srae) {}
783
}
784
```
785
786
### Asynchronous Processing
787
788
Non-blocking request processing for improved scalability.
789
790
```java { .api }
791
public interface AsyncContext {
792
static final String ASYNC_REQUEST_URI = "jakarta.servlet.async.request_uri";
793
static final String ASYNC_CONTEXT_PATH = "jakarta.servlet.async.context_path";
794
static final String ASYNC_PATH_INFO = "jakarta.servlet.async.path_info";
795
static final String ASYNC_SERVLET_PATH = "jakarta.servlet.async.servlet_path";
796
static final String ASYNC_QUERY_STRING = "jakarta.servlet.async.query_string";
797
static final String ASYNC_MAPPING = "jakarta.servlet.async.mapping";
798
799
ServletRequest getRequest();
800
ServletResponse getResponse();
801
boolean hasOriginalRequestAndResponse();
802
void dispatch();
803
void dispatch(String path);
804
void dispatch(ServletContext context, String path);
805
void complete();
806
void start(Runnable run);
807
void addListener(AsyncListener listener);
808
void addListener(AsyncListener listener, ServletRequest servletRequest,
809
ServletResponse servletResponse);
810
<T extends AsyncListener> T createListener(Class<T> clazz) throws ServletException;
811
void setTimeout(long timeout);
812
long getTimeout();
813
}
814
815
public interface AsyncListener extends EventListener {
816
void onComplete(AsyncEvent event) throws IOException;
817
void onTimeout(AsyncEvent event) throws IOException;
818
void onError(AsyncEvent event) throws IOException;
819
void onStartAsync(AsyncEvent event) throws IOException;
820
}
821
822
public class AsyncEvent {
823
public AsyncEvent(AsyncContext context);
824
public AsyncEvent(AsyncContext context, ServletRequest request, ServletResponse response);
825
public AsyncEvent(AsyncContext context, Throwable throwable);
826
public AsyncEvent(AsyncContext context, ServletRequest request, ServletResponse response,
827
Throwable throwable);
828
829
public AsyncContext getAsyncContext();
830
public ServletRequest getSuppliedRequest();
831
public ServletResponse getSuppliedResponse();
832
public Throwable getThrowable();
833
}
834
835
/**
836
* Listener for non-blocking read operations on ServletInputStream.
837
* Receives notifications when data is available to read.
838
*/
839
public interface ReadListener extends EventListener {
840
/** Invoked when data is available to read */
841
void onDataAvailable() throws IOException;
842
/** Invoked when all data has been read */
843
void onAllDataRead() throws IOException;
844
/** Invoked when an error occurs during reading */
845
void onError(Throwable t);
846
}
847
848
/**
849
* Listener for non-blocking write operations on ServletOutputStream.
850
* Receives notifications when it is possible to write data.
851
*/
852
public interface WriteListener extends EventListener {
853
/** Invoked when it is possible to write data without blocking */
854
void onWritePossible() throws IOException;
855
/** Invoked when an error occurs during writing */
856
void onError(Throwable t);
857
}
858
859
/**
860
* Provides connection metadata for servlet requests (introduced in Servlet 6.0).
861
*/
862
public interface ServletConnection {
863
/** Returns a connection identifier that is unique within the scope of the JVM */
864
String getConnectionId();
865
/** Returns the protocol used by the connection (e.g., "http/1.1", "h2") */
866
String getProtocol();
867
/** Returns an identifier for the protocol if the protocol provides one */
868
String getProtocolConnectionId();
869
/** Returns true if the connection is secure (HTTPS) */
870
boolean isSecure();
871
}
872
873
/**
874
* ServletInputStream with non-blocking I/O support.
875
*/
876
public abstract class ServletInputStream extends InputStream {
877
/** Reads input data into byte array */
878
public int readLine(byte[] b, int off, int len) throws IOException;
879
/** Returns true if all data has been read */
880
public abstract boolean isFinished();
881
/** Returns true if data can be read without blocking */
882
public abstract boolean isReady();
883
/** Sets the ReadListener for non-blocking I/O */
884
public abstract void setReadListener(ReadListener readListener);
885
}
886
887
/**
888
* ServletOutputStream with non-blocking I/O support.
889
*/
890
public abstract class ServletOutputStream extends OutputStream {
891
/** Writes a string to the output stream */
892
public void print(String s) throws IOException;
893
/** Writes a boolean to the output stream */
894
public void print(boolean b) throws IOException;
895
/** Writes a char to the output stream */
896
public void print(char c) throws IOException;
897
/** Writes an int to the output stream */
898
public void print(int i) throws IOException;
899
/** Writes a long to the output stream */
900
public void print(long l) throws IOException;
901
/** Writes a float to the output stream */
902
public void print(float f) throws IOException;
903
/** Writes a double to the output stream */
904
public void print(double d) throws IOException;
905
/** Writes a line separator */
906
public void println() throws IOException;
907
/** Writes a string followed by line separator */
908
public void println(String s) throws IOException;
909
/** Writes a boolean followed by line separator */
910
public void println(boolean b) throws IOException;
911
/** Writes a char followed by line separator */
912
public void println(char c) throws IOException;
913
/** Writes an int followed by line separator */
914
public void println(int i) throws IOException;
915
/** Writes a long followed by line separator */
916
public void println(long l) throws IOException;
917
/** Writes a float followed by line separator */
918
public void println(float f) throws IOException;
919
/** Writes a double followed by line separator */
920
public void println(double d) throws IOException;
921
/** Returns true if data can be written without blocking */
922
public abstract boolean isReady();
923
/** Sets the WriteListener for non-blocking I/O */
924
public abstract void setWriteListener(WriteListener writeListener);
925
}
926
```
927
928
**Configuration Note:** To enable asynchronous processing, servlets must be configured with async support either via the `@WebServlet(asyncSupported = true)` annotation or programmatically using `Wrapper.setAsyncSupported(true)`. Without this configuration, `request.isAsyncSupported()` returns false and async operations will fail.
929
930
**Non-Blocking I/O Example:**
931
932
```java
933
@WebServlet(urlPatterns = "/async-read", asyncSupported = true)
934
public class NonBlockingReadServlet extends HttpServlet {
935
@Override
936
protected void doPost(HttpServletRequest request, HttpServletResponse response)
937
throws ServletException, IOException {
938
AsyncContext asyncContext = request.startAsync();
939
ServletInputStream input = request.getInputStream();
940
941
input.setReadListener(new ReadListener() {
942
private ByteArrayOutputStream buffer = new ByteArrayOutputStream();
943
944
@Override
945
public void onDataAvailable() throws IOException {
946
byte[] bytes = new byte[1024];
947
int len;
948
while (input.isReady() && (len = input.read(bytes)) != -1) {
949
buffer.write(bytes, 0, len);
950
}
951
}
952
953
@Override
954
public void onAllDataRead() throws IOException {
955
byte[] data = buffer.toByteArray();
956
// Process the complete request data
957
response.getWriter().write("Received " + data.length + " bytes");
958
asyncContext.complete();
959
}
960
961
@Override
962
public void onError(Throwable t) {
963
asyncContext.complete();
964
}
965
});
966
}
967
}
968
```
969
970
### Multipart File Upload
971
972
Support for processing multipart/form-data requests.
973
974
```java { .api }
975
public interface Part {
976
InputStream getInputStream() throws IOException;
977
String getContentType();
978
String getName();
979
String getSubmittedFileName();
980
long getSize();
981
void write(String fileName) throws IOException;
982
void delete() throws IOException;
983
String getHeader(String name);
984
Collection<String> getHeaders(String name);
985
Collection<String> getHeaderNames();
986
}
987
988
public class MultipartConfigElement {
989
public MultipartConfigElement(String location);
990
public MultipartConfigElement(String location, long maxFileSize, long maxRequestSize,
991
int fileSizeThreshold);
992
public MultipartConfigElement(MultipartConfig annotation);
993
994
public String getLocation();
995
public long getMaxFileSize();
996
public long getMaxRequestSize();
997
public int getFileSizeThreshold();
998
}
999
```
1000
1001
**Configuration Note:** To use the Part interface for multipart file uploads, servlets must be configured with multipart support either via the `@MultipartConfig` annotation or programmatically using `Wrapper.setMultipartConfigElement(new MultipartConfigElement("/tmp"))`.
1002
1003
### Request Dispatcher
1004
1005
Forward and include functionality for internal request dispatching.
1006
1007
```java { .api }
1008
public interface RequestDispatcher {
1009
static final String FORWARD_REQUEST_URI = "jakarta.servlet.forward.request_uri";
1010
static final String FORWARD_CONTEXT_PATH = "jakarta.servlet.forward.context_path";
1011
static final String FORWARD_PATH_INFO = "jakarta.servlet.forward.path_info";
1012
static final String FORWARD_SERVLET_PATH = "jakarta.servlet.forward.servlet_path";
1013
static final String FORWARD_QUERY_STRING = "jakarta.servlet.forward.query_string";
1014
static final String FORWARD_MAPPING = "jakarta.servlet.forward.mapping";
1015
static final String INCLUDE_REQUEST_URI = "jakarta.servlet.include.request_uri";
1016
static final String INCLUDE_CONTEXT_PATH = "jakarta.servlet.include.context_path";
1017
static final String INCLUDE_PATH_INFO = "jakarta.servlet.include.path_info";
1018
static final String INCLUDE_SERVLET_PATH = "jakarta.servlet.include.servlet_path";
1019
static final String INCLUDE_QUERY_STRING = "jakarta.servlet.include.query_string";
1020
static final String INCLUDE_MAPPING = "jakarta.servlet.include.mapping";
1021
static final String ERROR_EXCEPTION = "jakarta.servlet.error.exception";
1022
static final String ERROR_EXCEPTION_TYPE = "jakarta.servlet.error.exception_type";
1023
static final String ERROR_MESSAGE = "jakarta.servlet.error.message";
1024
static final String ERROR_REQUEST_URI = "jakarta.servlet.error.request_uri";
1025
static final String ERROR_SERVLET_NAME = "jakarta.servlet.error.servlet_name";
1026
static final String ERROR_STATUS_CODE = "jakarta.servlet.error.status_code";
1027
1028
void forward(ServletRequest request, ServletResponse response)
1029
throws ServletException, IOException;
1030
void include(ServletRequest request, ServletResponse response)
1031
throws ServletException, IOException;
1032
}
1033
```
1034
1035
### Cookies
1036
1037
HTTP cookie management.
1038
1039
```java { .api }
1040
public class Cookie implements Cloneable {
1041
public Cookie(String name, String value);
1042
1043
public void setComment(String purpose);
1044
public String getComment();
1045
public void setDomain(String pattern);
1046
public String getDomain();
1047
public void setMaxAge(int expiry);
1048
public int getMaxAge();
1049
public void setPath(String uri);
1050
public String getPath();
1051
public void setSecure(boolean flag);
1052
public boolean getSecure();
1053
public String getName();
1054
public void setValue(String newValue);
1055
public String getValue();
1056
public int getVersion();
1057
public void setVersion(int v);
1058
public void setHttpOnly(boolean httpOnly);
1059
public boolean isHttpOnly();
1060
public void setAttribute(String name, String value);
1061
public String getAttribute(String name);
1062
public Map<String,String> getAttributes();
1063
public Object clone();
1064
}
1065
```
1066
1067
### Exceptions
1068
1069
```java { .api }
1070
public class ServletException extends Exception {
1071
public ServletException();
1072
public ServletException(String message);
1073
public ServletException(String message, Throwable rootCause);
1074
public ServletException(Throwable rootCause);
1075
public Throwable getRootCause();
1076
}
1077
1078
public class UnavailableException extends ServletException {
1079
public UnavailableException(String msg);
1080
public UnavailableException(String msg, int seconds);
1081
public boolean isPermanent();
1082
public int getUnavailableSeconds();
1083
}
1084
```
1085
1086
### Enumerations
1087
1088
```java { .api }
1089
public enum DispatcherType {
1090
FORWARD,
1091
INCLUDE,
1092
REQUEST,
1093
ASYNC,
1094
ERROR
1095
}
1096
```
1097
1098
### Annotations
1099
1100
```java { .api }
1101
// Servlet declaration
1102
@Target(ElementType.TYPE)
1103
@Retention(RetentionPolicy.RUNTIME)
1104
public @interface WebServlet {
1105
String name() default "";
1106
String[] value() default {};
1107
String[] urlPatterns() default {};
1108
int loadOnStartup() default -1;
1109
WebInitParam[] initParams() default {};
1110
boolean asyncSupported() default false;
1111
String smallIcon() default "";
1112
String largeIcon() default "";
1113
String description() default "";
1114
String displayName() default "";
1115
}
1116
1117
// Filter declaration
1118
@Target(ElementType.TYPE)
1119
@Retention(RetentionPolicy.RUNTIME)
1120
public @interface WebFilter {
1121
String filterName() default "";
1122
String[] value() default {};
1123
String[] urlPatterns() default {};
1124
DispatcherType[] dispatcherTypes() default {DispatcherType.REQUEST};
1125
WebInitParam[] initParams() default {};
1126
String[] servletNames() default {};
1127
boolean asyncSupported() default false;
1128
String smallIcon() default "";
1129
String largeIcon() default "";
1130
String description() default "";
1131
String displayName() default "";
1132
}
1133
1134
// Listener declaration
1135
@Target(ElementType.TYPE)
1136
@Retention(RetentionPolicy.RUNTIME)
1137
public @interface WebListener {
1138
String value() default "";
1139
}
1140
1141
// Initialization parameter
1142
@Target({})
1143
@Retention(RetentionPolicy.RUNTIME)
1144
public @interface WebInitParam {
1145
String name();
1146
String value();
1147
String description() default "";
1148
}
1149
1150
// Multipart configuration
1151
@Target(ElementType.TYPE)
1152
@Retention(RetentionPolicy.RUNTIME)
1153
public @interface MultipartConfig {
1154
String location() default "";
1155
long maxFileSize() default -1L;
1156
long maxRequestSize() default -1L;
1157
int fileSizeThreshold() default 0;
1158
}
1159
1160
// Security constraints
1161
@Target(ElementType.TYPE)
1162
@Retention(RetentionPolicy.RUNTIME)
1163
public @interface ServletSecurity {
1164
HttpConstraint value() default @HttpConstraint;
1165
HttpMethodConstraint[] httpMethodConstraints() default {};
1166
}
1167
1168
@Target({})
1169
@Retention(RetentionPolicy.RUNTIME)
1170
public @interface HttpConstraint {
1171
EmptyRoleSemantic value() default EmptyRoleSemantic.PERMIT;
1172
String[] rolesAllowed() default {};
1173
TransportGuarantee transportGuarantee() default TransportGuarantee.NONE;
1174
}
1175
1176
@Target({})
1177
@Retention(RetentionPolicy.RUNTIME)
1178
public @interface HttpMethodConstraint {
1179
String value();
1180
EmptyRoleSemantic emptyRoleSemantic() default EmptyRoleSemantic.PERMIT;
1181
String[] rolesAllowed() default {};
1182
TransportGuarantee transportGuarantee() default TransportGuarantee.NONE;
1183
}
1184
1185
public enum EmptyRoleSemantic {
1186
PERMIT,
1187
DENY
1188
}
1189
1190
public enum TransportGuarantee {
1191
NONE,
1192
CONFIDENTIAL
1193
}
1194
```
1195
1196
## Usage Examples
1197
1198
### Basic Servlet
1199
1200
```java
1201
import jakarta.servlet.ServletException;
1202
import jakarta.servlet.annotation.WebServlet;
1203
import jakarta.servlet.http.HttpServlet;
1204
import jakarta.servlet.http.HttpServletRequest;
1205
import jakarta.servlet.http.HttpServletResponse;
1206
import java.io.IOException;
1207
import java.io.PrintWriter;
1208
1209
@WebServlet(urlPatterns = "/hello", loadOnStartup = 1)
1210
public class HelloServlet extends HttpServlet {
1211
@Override
1212
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
1213
throws ServletException, IOException {
1214
resp.setContentType("text/html");
1215
PrintWriter out = resp.getWriter();
1216
out.println("<html><body>");
1217
out.println("<h1>Hello, " + req.getParameter("name") + "!</h1>");
1218
out.println("</body></html>");
1219
}
1220
}
1221
```
1222
1223
### Filter Example
1224
1225
```java
1226
import jakarta.servlet.*;
1227
import jakarta.servlet.annotation.WebFilter;
1228
import jakarta.servlet.http.HttpServletRequest;
1229
import java.io.IOException;
1230
1231
@WebFilter(urlPatterns = "/*")
1232
public class LoggingFilter implements Filter {
1233
@Override
1234
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
1235
throws IOException, ServletException {
1236
HttpServletRequest httpRequest = (HttpServletRequest) request;
1237
System.out.println("Request: " + httpRequest.getMethod() + " " + httpRequest.getRequestURI());
1238
long start = System.currentTimeMillis();
1239
1240
chain.doFilter(request, response);
1241
1242
long duration = System.currentTimeMillis() - start;
1243
System.out.println("Completed in " + duration + "ms");
1244
}
1245
}
1246
```
1247
1248
### Async Servlet Example
1249
1250
```java
1251
import jakarta.servlet.AsyncContext;
1252
import jakarta.servlet.ServletException;
1253
import jakarta.servlet.annotation.WebServlet;
1254
import jakarta.servlet.http.HttpServlet;
1255
import jakarta.servlet.http.HttpServletRequest;
1256
import jakarta.servlet.http.HttpServletResponse;
1257
import java.io.IOException;
1258
import java.io.PrintWriter;
1259
1260
@WebServlet(urlPatterns = "/async", asyncSupported = true)
1261
public class AsyncServlet extends HttpServlet {
1262
@Override
1263
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
1264
throws ServletException, IOException {
1265
AsyncContext asyncContext = req.startAsync();
1266
asyncContext.setTimeout(30000);
1267
1268
asyncContext.start(() -> {
1269
try {
1270
// Perform long-running operation
1271
Thread.sleep(5000);
1272
1273
PrintWriter out = asyncContext.getResponse().getWriter();
1274
out.println("Async operation completed");
1275
asyncContext.complete();
1276
} catch (Exception e) {
1277
e.printStackTrace();
1278
}
1279
});
1280
}
1281
}
1282
```
1283
1284
### Session Management Example
1285
1286
```java
1287
import jakarta.servlet.ServletException;
1288
import jakarta.servlet.annotation.WebServlet;
1289
import jakarta.servlet.http.HttpServlet;
1290
import jakarta.servlet.http.HttpServletRequest;
1291
import jakarta.servlet.http.HttpServletResponse;
1292
import jakarta.servlet.http.HttpSession;
1293
import java.io.IOException;
1294
1295
@WebServlet("/session-example")
1296
public class SessionServlet extends HttpServlet {
1297
@Override
1298
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
1299
throws ServletException, IOException {
1300
HttpSession session = req.getSession();
1301
1302
Integer visitCount = (Integer) session.getAttribute("visitCount");
1303
if (visitCount == null) {
1304
visitCount = 1;
1305
} else {
1306
visitCount++;
1307
}
1308
session.setAttribute("visitCount", visitCount);
1309
1310
resp.setContentType("text/plain");
1311
resp.getWriter().println("Visit count: " + visitCount);
1312
}
1313
}
1314
```
1315