0
# Servlet Lifecycle and Configuration
1
2
The Java Servlet API provides a comprehensive framework for servlet lifecycle management and configuration. This covers servlet initialization, context management, programmatic configuration, and deployment patterns.
3
4
## Core Servlet Interface
5
6
```java { .api }
7
/**
8
* The fundamental servlet interface that all servlets must implement.
9
* Defines the contract for servlet lifecycle and request processing.
10
*/
11
public interface Servlet {
12
/**
13
* Initialize the servlet with configuration parameters.
14
* Called once when the servlet is first loaded.
15
*/
16
void init(ServletConfig config) throws ServletException;
17
18
/**
19
* Get the servlet configuration object.
20
*/
21
ServletConfig getServletConfig();
22
23
/**
24
* Process a request and generate a response.
25
* Called for each request to this servlet.
26
*/
27
void service(ServletRequest req, ServletResponse res)
28
throws ServletException, IOException;
29
30
/**
31
* Return information about the servlet (version, author, etc.)
32
*/
33
String getServletInfo();
34
35
/**
36
* Cleanup resources when servlet is destroyed.
37
* Called once when servlet is removed from service.
38
*/
39
void destroy();
40
}
41
```
42
43
## ServletConfig Interface
44
45
```java { .api }
46
/**
47
* Configuration interface providing servlet initialization parameters
48
* and access to the servlet context.
49
*/
50
public interface ServletConfig {
51
/**
52
* Get the name of this servlet instance.
53
*/
54
String getServletName();
55
56
/**
57
* Get the servlet context for the web application.
58
*/
59
ServletContext getServletContext();
60
61
/**
62
* Get the value of a servlet initialization parameter.
63
*/
64
String getInitParameter(String name);
65
66
/**
67
* Get an enumeration of all initialization parameter names.
68
*/
69
Enumeration<String> getInitParameterNames();
70
}
71
```
72
73
## ServletContext Interface
74
75
```java { .api }
76
/**
77
* Interface representing the web application context.
78
* Provides access to application-wide resources and configuration.
79
*/
80
public interface ServletContext {
81
82
// Context path and version information
83
String getContextPath();
84
ServletContext getContext(String uripath);
85
int getMajorVersion();
86
int getMinorVersion();
87
int getEffectiveMajorVersion();
88
int getEffectiveMinorVersion();
89
90
// MIME type support
91
String getMimeType(String file);
92
93
// Resource access
94
Set<String> getResourcePaths(String path);
95
URL getResource(String path) throws MalformedURLException;
96
InputStream getResourceAsStream(String path);
97
RequestDispatcher getRequestDispatcher(String path);
98
RequestDispatcher getNamedDispatcher(String name);
99
100
// Logging
101
void log(String msg);
102
void log(String message, Throwable throwable);
103
104
// Real paths and server info
105
String getRealPath(String path);
106
String getServerInfo();
107
108
// Context initialization parameters
109
String getInitParameter(String name);
110
Enumeration<String> getInitParameterNames();
111
boolean setInitParameter(String name, String value);
112
113
// Context attributes
114
Object getAttribute(String name);
115
Enumeration<String> getAttributeNames();
116
void setAttribute(String name, Object object);
117
void removeAttribute(String name);
118
119
// Servlet name
120
String getServletContextName();
121
122
// Dynamic servlet registration
123
ServletRegistration.Dynamic addServlet(String servletName, String className);
124
ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet);
125
ServletRegistration.Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass);
126
<T extends Servlet> T createServlet(Class<T> clazz) throws ServletException;
127
ServletRegistration getServletRegistration(String servletName);
128
Map<String, ? extends ServletRegistration> getServletRegistrations();
129
130
// Dynamic filter registration
131
FilterRegistration.Dynamic addFilter(String filterName, String className);
132
FilterRegistration.Dynamic addFilter(String filterName, Filter filter);
133
FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass);
134
<T extends Filter> T createFilter(Class<T> clazz) throws ServletException;
135
FilterRegistration getFilterRegistration(String filterName);
136
Map<String, ? extends FilterRegistration> getFilterRegistrations();
137
138
// Session configuration
139
SessionCookieConfig getSessionCookieConfig();
140
void setSessionTrackingModes(Set<SessionTrackingMode> sessionTrackingModes);
141
Set<SessionTrackingMode> getDefaultSessionTrackingModes();
142
Set<SessionTrackingMode> getEffectiveSessionTrackingModes();
143
144
// Event listener management
145
void addListener(String className);
146
<T extends EventListener> void addListener(T t);
147
void addListener(Class<? extends EventListener> listenerClass);
148
<T extends EventListener> T createListener(Class<T> clazz) throws ServletException;
149
150
// JSP support
151
JspConfigDescriptor getJspConfigDescriptor();
152
153
// Class loader
154
ClassLoader getClassLoader();
155
156
// Declaration configuration
157
void declareRoles(String... roleNames);
158
159
// Virtual server name
160
String getVirtualServerName();
161
162
// Constants
163
public static final String TEMPDIR = "javax.servlet.context.tempdir";
164
public static final String ORDERED_LIBS = "javax.servlet.context.orderedLibs";
165
}
166
```
167
168
## GenericServlet Base Class
169
170
```java { .api }
171
/**
172
* Abstract base class providing default implementations for the Servlet interface.
173
* Implements ServletConfig methods by delegating to the actual config object.
174
*/
175
public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
176
177
private transient ServletConfig config;
178
179
/**
180
* Initialize the servlet and store the config.
181
*/
182
public void init(ServletConfig config) throws ServletException {
183
this.config = config;
184
this.init();
185
}
186
187
/**
188
* Convenience init method for subclasses to override.
189
*/
190
public void init() throws ServletException {
191
// Default implementation does nothing
192
}
193
194
/**
195
* Abstract service method that subclasses must implement.
196
*/
197
public abstract void service(ServletRequest req, ServletResponse res)
198
throws ServletException, IOException;
199
200
// ServletConfig delegation methods
201
public String getServletName() {
202
return config.getServletName();
203
}
204
205
public ServletContext getServletContext() {
206
return config.getServletContext();
207
}
208
209
public String getInitParameter(String name) {
210
return config.getInitParameter(name);
211
}
212
213
public Enumeration<String> getInitParameterNames() {
214
return config.getInitParameterNames();
215
}
216
217
public ServletConfig getServletConfig() {
218
return config;
219
}
220
221
/**
222
* Log a message to the servlet context log.
223
*/
224
public void log(String msg) {
225
getServletContext().log(getServletName() + ": " + msg);
226
}
227
228
public void log(String message, Throwable t) {
229
getServletContext().log(getServletName() + ": " + message, t);
230
}
231
232
public String getServletInfo() {
233
return "";
234
}
235
236
public void destroy() {
237
// Default implementation does nothing
238
}
239
}
240
```
241
242
## Servlet Registration Interfaces
243
244
```java { .api }
245
/**
246
* Base interface for servlet and filter registration.
247
*/
248
public interface Registration {
249
String getName();
250
String getClassName();
251
boolean setInitParameter(String name, String value);
252
String getInitParameter(String name);
253
Set<String> setInitParameters(Map<String, String> initParameters);
254
Map<String, String> getInitParameters();
255
256
/**
257
* Dynamic registration interface for runtime configuration changes.
258
*/
259
public interface Dynamic extends Registration {
260
void setAsyncSupported(boolean isAsyncSupported);
261
}
262
}
263
264
/**
265
* Servlet-specific registration interface.
266
*/
267
public interface ServletRegistration extends Registration {
268
269
/**
270
* Add servlet mappings for URL patterns.
271
*/
272
Set<String> addMapping(String... urlPatterns);
273
274
/**
275
* Get all URL mappings for this servlet.
276
*/
277
Collection<String> getMappings();
278
279
/**
280
* Get the run-as role for this servlet.
281
*/
282
String getRunAsRole();
283
284
/**
285
* Dynamic servlet registration interface.
286
*/
287
public interface Dynamic extends ServletRegistration, Registration.Dynamic {
288
void setLoadOnStartup(int loadOnStartup);
289
Set<String> setServletSecurity(ServletSecurityElement constraint);
290
void setMultipartConfig(MultipartConfigElement multipartConfig);
291
void setRunAsRole(String roleName);
292
}
293
}
294
295
/**
296
* Filter-specific registration interface.
297
*/
298
public interface FilterRegistration extends Registration {
299
300
/**
301
* Add filter mappings for URL patterns.
302
*/
303
void addMappingForUrlPatterns(EnumSet<DispatcherType> dispatcherTypes,
304
boolean isMatchAfter, String... urlPatterns);
305
306
/**
307
* Add filter mappings for servlet names.
308
*/
309
void addMappingForServletNames(EnumSet<DispatcherType> dispatcherTypes,
310
boolean isMatchAfter, String... servletNames);
311
312
/**
313
* Get URL pattern mappings.
314
*/
315
Collection<String> getUrlPatternMappings();
316
317
/**
318
* Get servlet name mappings.
319
*/
320
Collection<String> getServletNameMappings();
321
322
/**
323
* Dynamic filter registration interface.
324
*/
325
public interface Dynamic extends FilterRegistration, Registration.Dynamic {
326
// Inherits all methods from parent interfaces
327
}
328
}
329
```
330
331
## ServletContainerInitializer
332
333
```java { .api }
334
/**
335
* Interface for programmatic servlet container initialization.
336
* Implementations are discovered via ServiceLoader during container startup.
337
*/
338
public interface ServletContainerInitializer {
339
340
/**
341
* Called during container startup to perform programmatic configuration.
342
*
343
* @param c Set of classes that this initializer expressed interest in
344
* @param ctx The servlet context for programmatic configuration
345
*/
346
void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException;
347
}
348
```
349
350
## Configuration Examples
351
352
### Programmatic Servlet Configuration
353
354
```java { .api }
355
/**
356
* Example ServletContainerInitializer for programmatic configuration
357
*/
358
@HandlesTypes({Servlet.class, Filter.class})
359
public class MyAppInitializer implements ServletContainerInitializer {
360
361
@Override
362
public void onStartup(Set<Class<?>> classes, ServletContext ctx) throws ServletException {
363
364
// Add a servlet programmatically
365
ServletRegistration.Dynamic servlet = ctx.addServlet("MyServlet", MyServlet.class);
366
servlet.addMapping("/api/*");
367
servlet.setLoadOnStartup(1);
368
servlet.setAsyncSupported(true);
369
servlet.setInitParameter("config", "production");
370
371
// Add a filter programmatically
372
FilterRegistration.Dynamic filter = ctx.addFilter("MyFilter", MyFilter.class);
373
filter.addMappingForUrlPatterns(
374
EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD),
375
true, "/*"
376
);
377
filter.setAsyncSupported(true);
378
379
// Add listeners
380
ctx.addListener(MyContextListener.class);
381
ctx.addListener(MySessionListener.class);
382
383
// Configure session tracking
384
ctx.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE));
385
386
SessionCookieConfig cookieConfig = ctx.getSessionCookieConfig();
387
cookieConfig.setName("JSESSIONID");
388
cookieConfig.setHttpOnly(true);
389
cookieConfig.setSecure(true);
390
cookieConfig.setMaxAge(-1);
391
cookieConfig.setPath(ctx.getContextPath());
392
}
393
}
394
```
395
396
### Annotation-Based Configuration
397
398
```java { .api }
399
/**
400
* Servlet configured using annotations
401
*/
402
@WebServlet(
403
name = "ConfiguredServlet",
404
urlPatterns = {"/config", "/setup"},
405
loadOnStartup = 1,
406
initParams = {
407
@WebInitParam(name = "database.url", value = "jdbc:mysql://localhost/mydb"),
408
@WebInitParam(name = "pool.size", value = "10")
409
},
410
asyncSupported = true,
411
description = "Example configured servlet"
412
)
413
public class ConfiguredServlet extends HttpServlet {
414
415
private String databaseUrl;
416
private int poolSize;
417
418
@Override
419
public void init() throws ServletException {
420
// Access initialization parameters
421
databaseUrl = getInitParameter("database.url");
422
poolSize = Integer.parseInt(getInitParameter("pool.size"));
423
424
// Access servlet context
425
ServletContext context = getServletContext();
426
context.setAttribute("servlet.config", this);
427
428
log("Servlet initialized with database URL: " + databaseUrl);
429
}
430
431
@Override
432
protected void doGet(HttpServletRequest request, HttpServletResponse response)
433
throws ServletException, IOException {
434
435
response.setContentType("application/json");
436
PrintWriter out = response.getWriter();
437
438
out.println("{");
439
out.println(" \"servlet\": \"" + getServletName() + "\",");
440
out.println(" \"database\": \"" + databaseUrl + "\",");
441
out.println(" \"poolSize\": " + poolSize);
442
out.println("}");
443
}
444
445
@Override
446
public void destroy() {
447
// Cleanup resources
448
ServletContext context = getServletContext();
449
context.removeAttribute("servlet.config");
450
log("Servlet destroyed");
451
}
452
}
453
```
454
455
### WebInitParam Annotation
456
457
```java { .api }
458
/**
459
* Annotation used to specify initialization parameters for servlets and filters
460
*/
461
@Target({ElementType.TYPE})
462
@Retention(RetentionPolicy.RUNTIME)
463
@Documented
464
public @interface WebInitParam {
465
466
/**
467
* Name of the initialization parameter
468
* @return parameter name
469
*/
470
String name();
471
472
/**
473
* Value of the initialization parameter
474
* @return parameter value
475
*/
476
String value();
477
478
/**
479
* Description of the initialization parameter
480
* @return parameter description
481
*/
482
String description() default "";
483
}
484
```
485
486
### Context Attributes and Application State
487
488
```java { .api }
489
/**
490
* Example servlet demonstrating context attribute management
491
*/
492
public class StateManagementServlet extends HttpServlet {
493
494
@Override
495
public void init() throws ServletException {
496
ServletContext context = getServletContext();
497
498
// Initialize application-wide state
499
Map<String, Object> appConfig = new ConcurrentHashMap<>();
500
appConfig.put("startTime", System.currentTimeMillis());
501
appConfig.put("version", "1.0.0");
502
context.setAttribute("app.config", appConfig);
503
504
// Initialize counters
505
AtomicLong requestCounter = new AtomicLong(0);
506
context.setAttribute("request.counter", requestCounter);
507
}
508
509
@Override
510
protected void doGet(HttpServletRequest request, HttpServletResponse response)
511
throws ServletException, IOException {
512
513
ServletContext context = getServletContext();
514
515
// Access application state
516
Map<String, Object> appConfig =
517
(Map<String, Object>) context.getAttribute("app.config");
518
AtomicLong counter =
519
(AtomicLong) context.getAttribute("request.counter");
520
521
long currentRequest = counter.incrementAndGet();
522
long startTime = (Long) appConfig.get("startTime");
523
long uptime = System.currentTimeMillis() - startTime;
524
525
// Generate response
526
response.setContentType("application/json");
527
PrintWriter out = response.getWriter();
528
529
out.println("{");
530
out.println(" \"requestNumber\": " + currentRequest + ",");
531
out.println(" \"uptimeMs\": " + uptime + ",");
532
out.println(" \"version\": \"" + appConfig.get("version") + "\",");
533
out.println(" \"contextPath\": \"" + context.getContextPath() + "\",");
534
out.println(" \"serverInfo\": \"" + context.getServerInfo() + "\"");
535
out.println("}");
536
}
537
}
538
```
539
540
### Multi-Config Element Support
541
542
```java { .api }
543
/**
544
* Configuration element for multipart request handling
545
*/
546
public class MultipartConfigElement {
547
548
private final String location;
549
private final long maxFileSize;
550
private final long maxRequestSize;
551
private final int fileSizeThreshold;
552
553
public MultipartConfigElement(String location) {
554
this(location, -1L, -1L, 0);
555
}
556
557
public MultipartConfigElement(String location, long maxFileSize,
558
long maxRequestSize, int fileSizeThreshold) {
559
this.location = location;
560
this.maxFileSize = maxFileSize;
561
this.maxRequestSize = maxRequestSize;
562
this.fileSizeThreshold = fileSizeThreshold;
563
}
564
565
/**
566
* Get the directory location where files will be stored.
567
*/
568
public String getLocation() {
569
return location;
570
}
571
572
/**
573
* Get the maximum size allowed for uploaded files.
574
* -1 means unlimited.
575
*/
576
public long getMaxFileSize() {
577
return maxFileSize;
578
}
579
580
/**
581
* Get the maximum size allowed for multipart/form-data requests.
582
* -1 means unlimited.
583
*/
584
public long getMaxRequestSize() {
585
return maxRequestSize;
586
}
587
588
/**
589
* Get the size threshold after which files will be written to disk.
590
*/
591
public int getFileSizeThreshold() {
592
return fileSizeThreshold;
593
}
594
}
595
```
596
597
### Dispatcher Types Enum
598
599
```java { .api }
600
/**
601
* Enumeration of dispatcher types for filter mapping
602
*/
603
public enum DispatcherType {
604
605
/**
606
* Request came directly from the client (normal request)
607
*/
608
REQUEST,
609
610
/**
611
* Request is being forwarded to another resource
612
*/
613
FORWARD,
614
615
/**
616
* Request is including another resource
617
*/
618
INCLUDE,
619
620
/**
621
* Request is being processed asynchronously
622
*/
623
ASYNC,
624
625
/**
626
* Request is being processed due to an error
627
*/
628
ERROR
629
}
630
```
631
632
## Lifecycle Management Patterns
633
634
### Servlet Lifecycle States
635
636
```java { .api }
637
/**
638
* Complete servlet lifecycle example showing all phases
639
*/
640
public class LifecycleServlet extends HttpServlet {
641
642
private boolean initialized = false;
643
private long initTime;
644
private AtomicLong requestCount = new AtomicLong(0);
645
646
/**
647
* Initialization phase - called once when servlet is loaded
648
*/
649
@Override
650
public void init(ServletConfig config) throws ServletException {
651
super.init(config);
652
653
initTime = System.currentTimeMillis();
654
655
// Perform initialization logic
656
String configParam = getInitParameter("config.param");
657
if (configParam != null) {
658
// Process configuration
659
}
660
661
// Mark as initialized
662
initialized = true;
663
664
log("Servlet initialized at " + new Date(initTime));
665
}
666
667
/**
668
* Service phase - called for each request
669
*/
670
@Override
671
public void service(ServletRequest req, ServletResponse res)
672
throws ServletException, IOException {
673
674
if (!initialized) {
675
throw new ServletException("Servlet not properly initialized");
676
}
677
678
long requestNumber = requestCount.incrementAndGet();
679
log("Processing request #" + requestNumber);
680
681
// Delegate to HTTP-specific methods
682
super.service(req, res);
683
}
684
685
/**
686
* Destruction phase - called once when servlet is unloaded
687
*/
688
@Override
689
public void destroy() {
690
log("Destroying servlet after " + requestCount.get() + " requests");
691
692
// Cleanup resources
693
initialized = false;
694
requestCount.set(0);
695
696
// Perform cleanup logic
697
cleanupResources();
698
}
699
700
private void cleanupResources() {
701
// Close database connections, file handles, etc.
702
}
703
704
@Override
705
public String getServletInfo() {
706
return "Lifecycle demonstration servlet v1.0";
707
}
708
}
709
```
710
711
## JSP Configuration Descriptors
712
713
The servlet API provides programmatic access to JSP-related configuration through deployment descriptor interfaces.
714
715
### JspConfigDescriptor Interface
716
717
```java { .api }
718
/**
719
* Provides access to JSP-related configuration from web.xml and web-fragment.xml
720
*/
721
public interface JspConfigDescriptor {
722
723
/**
724
* Gets taglib child elements of the jsp-config element
725
* @return Collection of TaglibDescriptor objects
726
*/
727
Collection<TaglibDescriptor> getTaglibs();
728
729
/**
730
* Gets jsp-property-group child elements of the jsp-config element
731
* @return Collection of JspPropertyGroupDescriptor objects
732
*/
733
Collection<JspPropertyGroupDescriptor> getJspPropertyGroups();
734
}
735
```
736
737
### TaglibDescriptor Interface
738
739
```java { .api }
740
/**
741
* Provides access to taglib configuration from deployment descriptors
742
*/
743
public interface TaglibDescriptor {
744
745
/**
746
* Gets the unique identifier of the tag library
747
* @return the taglib URI
748
*/
749
String getTaglibURI();
750
751
/**
752
* Gets the location of the tag library
753
* @return the taglib location
754
*/
755
String getTaglibLocation();
756
}
757
```
758
759
### JspPropertyGroupDescriptor Interface
760
761
```java { .api }
762
/**
763
* Provides access to JSP property group configuration from deployment descriptors
764
*/
765
public interface JspPropertyGroupDescriptor {
766
767
/**
768
* Gets URL patterns of the JSP property group
769
* @return Collection of URL patterns
770
*/
771
Collection<String> getUrlPatterns();
772
773
/**
774
* Gets el-ignored configuration value
775
* @return el-ignored value or null if unspecified
776
*/
777
String getElIgnored();
778
779
/**
780
* Gets page-encoding configuration value
781
* @return page encoding or null if unspecified
782
*/
783
String getPageEncoding();
784
785
/**
786
* Gets scripting-invalid configuration value
787
* @return scripting-invalid value or null if unspecified
788
*/
789
String getScriptingInvalid();
790
791
/**
792
* Gets is-xml configuration value
793
* @return is-xml value or null if unspecified
794
*/
795
String getIsXml();
796
797
/**
798
* Gets include-prelude configuration
799
* @return Collection of include-prelude values
800
*/
801
Collection<String> getIncludePreludes();
802
803
/**
804
* Gets include-coda configuration
805
* @return Collection of include-coda values
806
*/
807
Collection<String> getIncludeCodas();
808
809
/**
810
* Gets deferred-syntax-allowed-as-literal configuration value
811
* @return deferred-syntax-allowed-as-literal value or null if unspecified
812
*/
813
String getDeferredSyntaxAllowedAsLiteral();
814
815
/**
816
* Gets trim-directive-whitespaces configuration value
817
* @return trim-directive-whitespaces value or null if unspecified
818
*/
819
String getTrimDirectiveWhitespaces();
820
821
/**
822
* Gets default-content-type configuration value
823
* @return default content type or null if unspecified
824
*/
825
String getDefaultContentType();
826
827
/**
828
* Gets buffer configuration value
829
* @return buffer value or null if unspecified
830
*/
831
String getBuffer();
832
833
/**
834
* Gets error-on-undeclared-namespace configuration value
835
* @return error-on-undeclared-namespace value or null if unspecified
836
*/
837
String getErrorOnUndeclaredNamespace();
838
}
839
```
840
841
This comprehensive coverage of servlet lifecycle and configuration provides the foundation for understanding how servlets are initialized, configured, and managed throughout their lifetime in the container.