0
# Apache Tomcat Embedded Core
1
2
Apache Tomcat Embedded Core provides a lightweight, embeddable servlet container for Java web applications. It includes the complete Jakarta Servlet 6.0 API implementation, HTTP/1.1 and HTTP/2 protocol support via Coyote connectors, the Catalina servlet engine with full lifecycle management, and the JULI logging framework. This library enables developers to embed a production-ready Tomcat server directly into Java applications without requiring external servlet container deployments.
3
4
## Package Information
5
6
- **Package Name**: org.apache.tomcat.embed:tomcat-embed-core
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Version**: 10.1.41
10
- **Installation**: Add Maven dependency:
11
12
```xml
13
<dependency>
14
<groupId>org.apache.tomcat.embed</groupId>
15
<artifactId>tomcat-embed-core</artifactId>
16
<version>10.1.41</version>
17
</dependency>
18
```
19
20
## Core Imports
21
22
```java
23
// Embedded Tomcat startup
24
import org.apache.catalina.startup.Tomcat;
25
import org.apache.catalina.Context;
26
import org.apache.catalina.LifecycleException;
27
28
// Jakarta Servlet API
29
import jakarta.servlet.Servlet;
30
import jakarta.servlet.ServletException;
31
import jakarta.servlet.http.HttpServlet;
32
import jakarta.servlet.http.HttpServletRequest;
33
import jakarta.servlet.http.HttpServletResponse;
34
35
// Catalina core containers
36
import org.apache.catalina.Engine;
37
import org.apache.catalina.Host;
38
import org.apache.catalina.Wrapper;
39
import org.apache.catalina.connector.Connector;
40
```
41
42
## Basic Usage
43
44
```java
45
import org.apache.catalina.startup.Tomcat;
46
import org.apache.catalina.Context;
47
import org.apache.catalina.LifecycleException;
48
import jakarta.servlet.ServletException;
49
import jakarta.servlet.http.HttpServlet;
50
import jakarta.servlet.http.HttpServletRequest;
51
import jakarta.servlet.http.HttpServletResponse;
52
import java.io.File;
53
import java.io.IOException;
54
import java.io.PrintWriter;
55
56
public class EmbeddedTomcatExample {
57
public static void main(String[] args) throws LifecycleException {
58
// Create Tomcat instance
59
Tomcat tomcat = new Tomcat();
60
tomcat.setPort(8080);
61
tomcat.setBaseDir(new File("target/tomcat").getAbsolutePath());
62
63
// Add a simple context
64
Context ctx = tomcat.addContext("", new File(".").getAbsolutePath());
65
66
// Add a servlet
67
HttpServlet helloServlet = new HttpServlet() {
68
@Override
69
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
70
throws ServletException, IOException {
71
resp.setContentType("text/html");
72
PrintWriter writer = resp.getWriter();
73
writer.println("<h1>Hello from Embedded Tomcat!</h1>");
74
}
75
};
76
77
Tomcat.addServlet(ctx, "helloServlet", helloServlet);
78
ctx.addServletMappingDecoded("/hello", "helloServlet");
79
80
// Start the server
81
tomcat.start();
82
tomcat.getServer().await();
83
}
84
}
85
```
86
87
## Architecture
88
89
Apache Tomcat Embedded Core implements a modular architecture with distinct subsystems:
90
91
### Catalina Servlet Engine
92
93
The core container hierarchy implements nested component management:
94
95
- **Server**: Top-level singleton representing the entire Tomcat instance
96
- **Service**: Groups one or more Connectors with a single Engine
97
- **Engine**: Container managing virtual hosts, processes all requests for a Service
98
- **Host**: Virtual host container managing web application contexts
99
- **Context**: Web application container, represents a single web app with its servlets
100
- **Wrapper**: Individual servlet container, wraps a single servlet instance
101
102
Each container implements the **Lifecycle** interface for consistent initialization, startup, shutdown, and destruction across the component hierarchy.
103
104
### Coyote Connectors
105
106
Protocol handlers manage network communication:
107
108
- **HTTP/1.1 Connector**: Handles HTTP/1.1 requests with NIO, NIO2, or APR/native implementations
109
- **HTTP/2 Connector**: Provides HTTP/2 support with multiplexing and server push
110
- **AJP Connector**: Apache JServ Protocol for integration with Apache HTTP Server
111
112
Connectors use **ProtocolHandler** implementations to process requests and generate responses through the **Request** and **Response** objects.
113
114
### Pipeline and Valve Architecture
115
116
Request processing uses a chain-of-responsibility pattern:
117
118
- **Pipeline**: Each container (Engine, Host, Context, Wrapper) has a Pipeline
119
- **Valve**: Processing component in the pipeline, performs specific operations on requests
120
- Valves enable cross-cutting concerns like logging, authentication, access control, and compression
121
122
### JULI Logging Framework
123
124
Tomcat's Java Util Logging Implementation provides:
125
126
- Per-classloader logging isolation for web applications
127
- Bridge to java.util.logging API
128
- Configurable log handlers and formatters
129
- Support for file rotation and console output
130
131
## Capabilities
132
133
### Jakarta Servlet API
134
135
Complete implementation of Jakarta Servlet 6.0 specification including servlets, filters, listeners, request/response handling, sessions, async processing, and security constraints.
136
137
```java { .api }
138
// Core servlet interface
139
public interface Servlet {
140
void init(ServletConfig config) throws ServletException;
141
void service(ServletRequest req, ServletResponse res) throws ServletException, IOException;
142
void destroy();
143
ServletConfig getServletConfig();
144
String getServletInfo();
145
}
146
147
// HTTP servlet base class
148
public abstract class HttpServlet extends GenericServlet {
149
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
150
throws ServletException, IOException;
151
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
152
throws ServletException, IOException;
153
protected void doPut(HttpServletRequest req, HttpServletResponse resp)
154
throws ServletException, IOException;
155
protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
156
throws ServletException, IOException;
157
}
158
159
// Servlet context interface
160
public interface ServletContext {
161
String getContextPath();
162
ServletContext getContext(String uripath);
163
RequestDispatcher getRequestDispatcher(String path);
164
void setAttribute(String name, Object object);
165
Object getAttribute(String name);
166
void log(String msg);
167
}
168
```
169
170
[Jakarta Servlet API](./servlet-api.md)
171
172
### Embedded Tomcat Startup
173
174
Simplified API for programmatically creating and configuring embedded Tomcat instances with contexts, servlets, and connectors.
175
176
```java { .api }
177
public class Tomcat {
178
public Tomcat();
179
public void setPort(int port);
180
public void setBaseDir(String basedir);
181
public void setHostname(String s);
182
183
// Add web applications
184
public Context addWebapp(String contextPath, String docBase);
185
public Context addContext(String contextPath, String docBase);
186
187
// Add servlets
188
public Wrapper addServlet(String contextPath, String servletName, String servletClass);
189
public Wrapper addServlet(String contextPath, String servletName, Servlet servlet);
190
public static Wrapper addServlet(Context ctx, String servletName, Servlet servlet);
191
192
// Lifecycle management
193
public void init() throws LifecycleException;
194
public void start() throws LifecycleException;
195
public void stop() throws LifecycleException;
196
public void destroy() throws LifecycleException;
197
198
// Access components
199
public Server getServer();
200
public Service getService();
201
public Engine getEngine();
202
public Host getHost();
203
public Connector getConnector();
204
public void setConnector(Connector connector);
205
}
206
```
207
208
[Embedded Tomcat API](./embedded-tomcat.md)
209
210
### Catalina Core Containers
211
212
Container hierarchy (Server, Service, Engine, Host, Context, Wrapper) with lifecycle management, nested component relationships, and request processing pipelines.
213
214
```java { .api }
215
// Base container interface
216
public interface Container extends Lifecycle {
217
String getName();
218
void setName(String name);
219
Container getParent();
220
void setParent(Container container);
221
void addChild(Container child);
222
Container findChild(String name);
223
Container[] findChildren();
224
Pipeline getPipeline();
225
Realm getRealm();
226
void setRealm(Realm realm);
227
}
228
229
// Context interface (web application)
230
public interface Context extends Container {
231
void setPath(String path);
232
String getPath();
233
void setDocBase(String docBase);
234
String getDocBase();
235
void addServletContainerInitializer(
236
ServletContainerInitializer sci, Set<Class<?>> classes);
237
void addApplicationListener(String listener);
238
void addServletMappingDecoded(String pattern, String name);
239
}
240
241
// Lifecycle interface
242
public interface Lifecycle {
243
void addLifecycleListener(LifecycleListener listener);
244
void removeLifecycleListener(LifecycleListener listener);
245
void init() throws LifecycleException;
246
void start() throws LifecycleException;
247
void stop() throws LifecycleException;
248
void destroy() throws LifecycleException;
249
LifecycleState getState();
250
String getStateName();
251
}
252
```
253
254
[Catalina Core Containers](./catalina-core.md)
255
256
### HTTP and Protocol Connectors
257
258
Coyote connector architecture supporting HTTP/1.1, HTTP/2, and AJP protocols with configurable thread pools, connection limits, and protocol handlers.
259
260
```java { .api }
261
public class Connector extends LifecycleMBeanBase {
262
public Connector();
263
public Connector(String protocol);
264
265
// Protocol configuration
266
public String getProtocol();
267
public String getScheme();
268
public void setScheme(String scheme);
269
public boolean getSecure();
270
public void setSecure(boolean secure);
271
272
// Network configuration
273
public int getPort();
274
public void setPort(int port);
275
public int getPortWithOffset();
276
277
// Protocol handler properties (delegated via reflection)
278
// Use setProperty to configure: maxThreads, connectionTimeout, maxConnections, etc.
279
public boolean setProperty(String name, String value);
280
public Object getProperty(String name);
281
282
// Request/response handling
283
public Request createRequest();
284
public Response createResponse();
285
}
286
```
287
288
[Connectors and Protocols](./connectors.md)
289
290
### Authentication and Security
291
292
Comprehensive authentication support including BASIC, DIGEST, FORM, CLIENT-CERT authenticators, realm implementations for user/role management, and Jakarta Authentication (JASPIC) integration.
293
294
```java { .api }
295
// Realm interface for authentication
296
public interface Realm {
297
Principal authenticate(String username, String credentials);
298
Principal authenticate(String username, String digest, String nonce,
299
String nc, String cnonce, String qop, String realm, String md5a2);
300
Principal authenticate(X509Certificate[] certs);
301
Principal authenticate(GSSContext gssContext, boolean storeCreds);
302
boolean hasRole(Wrapper wrapper, Principal principal, String role);
303
void setCredentialHandler(CredentialHandler credentialHandler);
304
CredentialHandler getCredentialHandler();
305
}
306
307
// JASPIC ServerAuthModule
308
public interface ServerAuthModule {
309
void initialize(MessagePolicy requestPolicy, MessagePolicy responsePolicy,
310
CallbackHandler handler, Map<String,Object> options) throws AuthException;
311
AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject,
312
Subject serviceSubject) throws AuthException;
313
AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject)
314
throws AuthException;
315
void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException;
316
}
317
```
318
319
[Authentication and Security](./authentication.md)
320
321
### Session Management
322
323
HTTP session tracking with configurable persistence stores, clustering support, session ID generation, and timeout management.
324
325
```java { .api }
326
// Manager interface for session management
327
public interface Manager {
328
Context getContext();
329
void setContext(Context context);
330
331
// Session operations
332
void add(Session session);
333
Session createSession(String sessionId);
334
Session findSession(String id) throws IOException;
335
void remove(Session session);
336
void remove(Session session, boolean update);
337
338
// Session configuration
339
int getMaxInactiveInterval();
340
void setMaxInactiveInterval(int interval);
341
int getSessionIdLength();
342
void setSessionIdLength(int length);
343
344
// Statistics
345
int getActiveSessions();
346
long getExpiredSessions();
347
void setExpiredSessions(long expiredSessions);
348
int getRejectedSessions();
349
}
350
351
// Session interface
352
public interface Session {
353
String getId();
354
void setId(String id);
355
Manager getManager();
356
void setManager(Manager manager);
357
long getCreationTime();
358
long getLastAccessedTime();
359
int getMaxInactiveInterval();
360
void setMaxInactiveInterval(int interval);
361
void access();
362
void expire();
363
}
364
```
365
366
[Session Management](./session-management.md)
367
368
### Valve Pipeline
369
370
Request processing pipeline with valves for cross-cutting concerns including access logging, authentication, compression, rewriting, and custom request/response processing.
371
372
```java { .api }
373
// Valve interface
374
public interface Valve {
375
Valve getNext();
376
void setNext(Valve valve);
377
void invoke(Request request, Response response) throws IOException, ServletException;
378
boolean isAsyncSupported();
379
void backgroundProcess();
380
}
381
382
// Pipeline interface
383
public interface Pipeline extends Contained {
384
Valve getBasic();
385
void setBasic(Valve valve);
386
void addValve(Valve valve);
387
Valve[] getValves();
388
void removeValve(Valve valve);
389
Valve getFirst();
390
boolean isAsyncSupported();
391
}
392
393
// Common valve types
394
public abstract class ValveBase extends LifecycleMBeanBase implements Valve {
395
protected Valve next;
396
public Valve getNext();
397
public void setNext(Valve valve);
398
public abstract void invoke(Request request, Response response)
399
throws IOException, ServletException;
400
}
401
```
402
403
[Valves and Pipeline](./valves.md)
404
405
### Web Resources
406
407
Resource management system for serving static content, loading classes, and accessing JAR files with support for multiple resource sets, caching, and virtual directories.
408
409
```java { .api }
410
// WebResourceRoot interface
411
public interface WebResourceRoot extends Lifecycle {
412
WebResource getResource(String path);
413
WebResource getClassLoaderResource(String path);
414
WebResource[] getResources(String path);
415
WebResource[] getClassLoaderResources(String path);
416
WebResource[] listResources(String path);
417
418
// Resource set management
419
void addPreResources(WebResourceSet webResourceSet);
420
void addJarResources(WebResourceSet webResourceSet);
421
void addPostResources(WebResourceSet webResourceSet);
422
void createWebResourceSet(ResourceSetType type, String webAppMount,
423
String base, String archivePath, String internalPath);
424
425
// Configuration
426
void setCachingAllowed(boolean cachingAllowed);
427
boolean isCachingAllowed();
428
void setCacheTtl(long ttl);
429
long getCacheTtl();
430
}
431
432
// WebResource interface
433
public interface WebResource {
434
long getLastModified();
435
String getLastModifiedHttp();
436
boolean exists();
437
boolean isVirtual();
438
boolean isDirectory();
439
boolean isFile();
440
String getName();
441
long getContentLength();
442
String getCanonicalPath();
443
boolean canRead();
444
String getWebappPath();
445
InputStream getInputStream();
446
byte[] getContent();
447
}
448
```
449
450
[Web Resources](./web-resources.md)
451
452
### JULI Logging
453
454
Tomcat's Java Util Logging Implementation providing per-classloader log isolation, configurable handlers, formatters, and integration with java.util.logging.
455
456
```java { .api }
457
// JULI Log interface (commons-logging compatible)
458
public interface Log {
459
boolean isDebugEnabled();
460
boolean isErrorEnabled();
461
boolean isFatalEnabled();
462
boolean isInfoEnabled();
463
boolean isTraceEnabled();
464
boolean isWarnEnabled();
465
466
void trace(Object message);
467
void trace(Object message, Throwable t);
468
void debug(Object message);
469
void debug(Object message, Throwable t);
470
void info(Object message);
471
void info(Object message, Throwable t);
472
void warn(Object message);
473
void warn(Object message, Throwable t);
474
void error(Object message);
475
void error(Object message, Throwable t);
476
void fatal(Object message);
477
void fatal(Object message, Throwable t);
478
}
479
480
// LogFactory for obtaining Log instances
481
public class LogFactory {
482
public static Log getLog(Class<?> clazz);
483
public static Log getLog(String name);
484
}
485
```
486
487
[JULI Logging](./logging.md)
488
489
### Utility Classes
490
491
Comprehensive utility libraries including HTTP parsing, byte buffers, character encoding, networking utilities, threading utilities, URI encoding, MIME type handling, and collection utilities.
492
493
```java { .api }
494
// ByteChunk for efficient byte buffer management
495
public final class ByteChunk implements Cloneable, Serializable {
496
public void setBytes(byte[] b, int off, int len);
497
public byte[] getBytes();
498
public int getStart();
499
public int getEnd();
500
public int getLength();
501
public void recycle();
502
public void append(byte b) throws IOException;
503
}
504
505
// MessageBytes for efficient string/byte conversion
506
public final class MessageBytes implements Cloneable, Serializable {
507
public static final int T_NULL = 0;
508
public static final int T_STR = 1;
509
public static final int T_BYTES = 2;
510
public static final int T_CHARS = 3;
511
512
public void setString(String s);
513
public String toString();
514
public ByteChunk getByteChunk();
515
public CharChunk getCharChunk();
516
public int getType();
517
}
518
519
// B2CConverter for byte-to-char encoding conversion
520
public class B2CConverter {
521
public B2CConverter(Charset charset);
522
public void convert(ByteChunk bb, CharChunk cb) throws IOException;
523
public void recycle();
524
}
525
```
526
527
[Utility Classes](./utilities.md)
528
529
## Common Types
530
531
Types used across multiple capabilities:
532
533
```java { .api }
534
// LifecycleException
535
public final class LifecycleException extends Exception {
536
public LifecycleException();
537
public LifecycleException(String message);
538
public LifecycleException(Throwable throwable);
539
public LifecycleException(String message, Throwable throwable);
540
}
541
542
// ServletException (Jakarta Servlet API)
543
public class ServletException extends Exception {
544
public ServletException();
545
public ServletException(String message);
546
public ServletException(String message, Throwable rootCause);
547
public ServletException(Throwable rootCause);
548
public Throwable getRootCause();
549
}
550
551
// LifecycleState enum
552
public enum LifecycleState {
553
NEW,
554
INITIALIZING,
555
INITIALIZED,
556
STARTING_PREP,
557
STARTING,
558
STARTED,
559
STOPPING_PREP,
560
STOPPING,
561
STOPPED,
562
DESTROYING,
563
DESTROYED,
564
FAILED;
565
566
public boolean isAvailable();
567
public String getLifecycleEvent();
568
}
569
```
570
571
## Key Design Patterns
572
573
### Component Lifecycle
574
575
All major Tomcat components implement a consistent lifecycle:
576
577
1. **NEW**: Component created but not initialized
578
2. **INITIALIZING/INITIALIZED**: One-time initialization
579
3. **STARTING/STARTED**: Component active and processing requests
580
4. **STOPPING/STOPPED**: Graceful shutdown in progress
581
5. **DESTROYING/DESTROYED**: Cleanup and resource release
582
6. **FAILED**: Error state requiring manual intervention
583
584
### Chain of Responsibility
585
586
Valves in pipelines process requests sequentially, with each valve deciding whether to continue the chain or terminate processing.
587
588
### Facade Pattern
589
590
Request and Response facades protect internal Catalina objects from direct access by application code, providing security and encapsulation.
591
592
## Thread Safety
593
594
- **Container components**: Thread-safe, accessed concurrently by request processing threads
595
- **Request/Response objects**: Not thread-safe, bound to single request processing thread
596
- **Session objects**: Synchronized methods for thread-safe attribute access
597
- **Servlet instances**: Must be thread-safe per servlet specification
598
599
## Performance Considerations
600
601
- **Connection pooling**: Configure maxThreads and maxConnections for optimal throughput
602
- **Resource caching**: Enable WebResourceRoot caching for static resources
603
- **Compression**: Use CompressionValve for compressing responses
604
- **Session persistence**: Choose appropriate Manager implementation (standard, persistent, cluster)
605
- **Logging**: Configure appropriate log levels; excessive debug logging impacts performance
606
607
## Migration Notes
608
609
For applications migrating from Java EE to Jakarta EE:
610
611
- Package namespace changed from `javax.servlet` to `jakarta.servlet`
612
- All servlet, filter, and listener classes must import Jakarta packages
613
- Web descriptor schemas updated to Jakarta namespace
614
- Tomcat 10.x supports Jakarta Servlet 5.0/6.0 (not javax.servlet)
615