Tomcat Server - Servlet Container
Source: Dev.to
What is a Servlet?
In Java web development, a Servlet is a Java class that:
- Receives an HTTP request
- Returns an HTTP response
Typical flow:
Browser → Servlet → Response (HTML / JSON)
Example
GET /login
The servlet runs Java code and returns:
## Welcome
Note: A servlet cannot run by itself; it needs a container.
What is a Servlet Container?
A Servlet Container is software that:
- Starts your servlets
- Opens a port (e.g., 8080)
- Accepts browser requests
- Executes servlet Java code
In other words, it provides the runtime environment for servlets.
What is Tomcat?
Tomcat acts as the servlet container for Spring applications.
- Opens a port (default 8080)
- Understands HTTP
- Runs servlets
- Manages the lifecycle of web apps
Without Tomcat, a Spring web app is just a collection of Java files that cannot be accessed via a browser.
Relationship with Spring Boot
Spring Boot Application
↓
Runs inside Tomcat
↓
Tomcat runs inside the JVM
What Happens When You Run a Spring Boot App?
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
When the application starts:
- Spring Boot starts an embedded Tomcat instance.
- Registers Spring as a servlet.
- Tomcat listens on port 8080.
- Incoming requests are forwarded to Spring.
- Spring executes the appropriate controllers.
The spring-boot-starter-web dependency (included by default) brings in spring-boot-starter-tomcat, which provides the embedded Tomcat server.
Spring Boot creates a single main servlet called DispatcherServlet, which serves as Spring’s front controller.
What Is DispatcherServlet?
DispatcherServlet is a special servlet written by Spring. Since Tomcat can only talk to servlets, it forwards all incoming requests to this servlet.
Typical flow:
Browser
↓
Tomcat
↓
DispatcherServlet (Spring)
↓
Your @Controller / @RestController
Example Mapping
One DispatcherServlet
├─ "/login" → login()
├─ "/register" → register()
└─ "/products" → products()
Thus, Spring uses a single servlet to handle thousands of routes.
What Happens Internally When You Hit a URL in Spring Boot?
Assume you browse to http://localhost:8080/hello.
-
Browser sends HTTP request
GET /hello Host: localhost:8080 -
Tomcat (Web Server) receives the request
- Listens on port 8080.
- Forwards the request to the registered
DispatcherServlet.
-
DispatcherServletreceives the request- Handles
GET /hello.
- Handles
-
HandlerMapping
- Spring looks up the URL in its
HandlerMappingregistry. - Finds the mapping:
/hello → HelloController.hello().
- Spring looks up the URL in its
-
Controller execution
- Spring invokes the corresponding controller method.
During startup, Spring builds a map of URL patterns to controller methods, e.g.:
| Annotation | Returns |
|---|---|
@RestController | @Controller + @ResponseBody |
This mapping enables Spring to route requests efficiently without needing multiple servlets.