How a Java Server Really Works: Servlets Explained

2026-12-02来源 dev.toEnglish

If you have built a server in Node.js, you probably remember the first time you saw this:

const http = require("http"); const server = http.createServer((req, res) => { res.end("Hello!"); }); server.listen(8080); 

Five lines, and you have a server. No framework. No magic. Just req coming in and res going out.
Then you open a Spring Boot project and meet annotations, controllers, and a dozen things you never wrote. Where did the server go?

In this article, I will show you that it never went anywhere. Java does the same job as Node, with the same pieces. The only difference is who builds the building.
I will explain everything with one story, so even a nursery school child could follow along. Let's go to a restaurant.

Part 1: What happens when you visit a website

Imagine you are hungry. You walk into a restaurant, write what you want on a small paper slip, and hand it over. A little later, a plate of food comes back to your table.
The internet works the same way:

  • You are the browser (or Postman).
  • The paper slip is the request: "I want the pizza."
  • The plate of food is the response.
  • The restaurant is the server.

A request has a few simple parts:

  • A method: what kind of thing you want to do. GET means "give me something". POST means "here is something new for you".
  • A path: where you want to go, like /firstServlet.
  • Sometimes a body: extra information, like your name and your city.

The server's only job is to read the slip and send back a plate. That is all HTTP is.

Part 2: Building the whole restaurant yourself (Node)

In Node, you build the restaurant from the ground up. Look at it again, with a little more inside:

const http = require("http"); const server = http.createServer((req, res) => { if (req.url === "/firstServlet" && req.method === "POST") { res.end("Hello from the pizza station!"); } else { res.statusCode = 404; res.end("We do not sell that here."); } }); server.listen(8080); 

Here is the story:

  • http.createServer builds the restaurant building.
  • server.listen(8080) opens the front door. Port 8080 is the door number.
  • The function (req, res) => {...} is the one person who handles every customer.
  • The if statements are the people reading the slip and deciding what to do.

That last part has a name: routing. In plain Node, you are the one who does the routing, with if statements. Express and other frameworks simply hide those if statements behind nicer words like app.get("/hello").
Remember this. It matters in a minute.

Part 3: Java can build the building too

Here is a surprise: Java can do the Node thing. It has a tiny built-in server:

import com.sun.net.httpserver.HttpServer; import java.io.OutputStream; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; public class TinyServer { public static void main(String[] args) throws Exception { HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0); server.createContext("/hello", exchange -> { byte[] body = "Hello from Java!".getBytes(StandardCharsets.UTF_8); exchange.sendResponseHeaders(200, body.length); try (OutputStream os = exchange.getResponseBody()) { os.write(body); } }); server.start(); } } 

Compare it to Node:

Node Java
http.createServer(...) HttpServer.create(...)
server.listen(8080) server.start()
(req, res) => {...} the lambda inside createContext

Same idea. Build a server, open a door, give it a function to run. This is the "from first principles" version, and it is what the bigger tools are built on.
But most Java developers do not write it this way. Why? Because Java has a different tradition.

Part 4: Hiring a restaurant manager (the Servlet Container)

In the Java world, people decide: "Building the restaurant every time is boring. Let's build one great restaurant building, called a container, and let everyone else just bring their cooks."

The most famous container is Tomcat.
Here is the new story:

  • Tomcat is the restaurant building. It opens port 8080, listens for customers, and reads the paper slips.
  • A Servlet is a cook. You write the cook, and Tomcat decides when to call the cook.
  • You never build the building. You only train the cook.

The big idea is called inversion of control, which is a fancy way of saying: "Don't call us, we'll call you." In Node, your code creates the server and calls everything. In Java, the container creates your servlet and calls you.

Part 5: Your first cook (a Servlet)

Here is a real servlet:

@WebServlet("/firstServlet") public class WebServletApp extends HttpServlet { public WebServletApp() { System.out.println("FirstServlet object is created by the container"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String name = req.getParameter("uname"); String ucity = req.getParameter("ucity"); resp.setContentType("text/plain;charset=UTF-8"); try (PrintWriter writer = resp.getWriter()) { writer.println("Hello " + name); writer.println("I know you're from " + ucity); } } } 

Let's read it like a story:

  • @WebServlet("/firstServlet") is a name tag on the cook's station. It tells Tomcat: "Any slip that says /firstServlet comes to me."
  • extends HttpServlet means: "I am a trained cook who already knows the basics of the job."
  • doPost is what this cook does when someone says POST, "here is something new".
  • req is the paper slip. req.getParameter("uname") reads the name written on it.
  • resp is the plate. Whatever we write to it goes back to the customer.

Notice what this cook does not do. It never opens a door. It never listens on a port. It never reads raw bytes. Tomcat did all of that already.

Part 6: The journey of one order (Dispatching)

Now the main question: how does the right cook get the right slip? This is called dispatching. Here is the journey of one request:

  1. A customer arrives. Raw bytes come in through port 8080. Tomcat is waiting.
  2. Tomcat reads the slip. It turns the bytes into a neat HttpServletRequest object, and prepares an empty HttpServletResponse (an empty plate).
  3. Tomcat finds the right station. It looks at the path, /firstServlet, and checks its list of name tags. It finds WebServletApp.
  4. Tomcat wakes the cook, if needed. If this cook has never worked before, Tomcat creates one instance of the servlet and calls init(). This happens only once.
  5. Tomcat calls service(). This is the cook's front-desk method. It looks at the HTTP method on the slip.
  6. The cook picks the right job. If the slip says POST, service() calls doPost. If it says GET, it calls doGet.
  7. Your code runs and fills the plate.
  8. Tomcat carries the plate back to the customer.

So there are two decisions in total:

  • Tomcat chooses the servlet by looking at the path.
  • HttpServlet chooses the method by looking at the HTTP verb. That is the answer to "how does dispatching work?" It is two lookups.

Failures that can happen

GET request failure?
If you send a GET to the servlet above, you will get 405 Method Not Allowed. The cook only knows doPost. Nobody taught this cook doGet, so when a GET slip arrives, the cook says, "Sorry, I don't do that job."

The cook's life

A servlet has a short life with three big moments, called the lifecycle:

  • init(): the cook's first day. Called once.
  • service() and doGet/doPost: the cook working. Called for every order.
  • destroy(): the cook goes home. Called when the restaurant closes.

Tomcat creates one cook and reuses that same cook for every customer. One cook, many orders. So a servlet should never keep a customer's private information in its own pockets (instance fields), because the next customer would see it.

Part 7: Where does Spring Boot fit in?

Now the big reveal. Spring Boot is not a different way of doing HTTP. It sits on top of what you just learned.
When a Spring Boot web app starts, it:

  1. Starts an embedded Tomcat. You did not install it. It came inside your app.
  2. Registers one special servlet called the DispatcherServlet, mapped to /.

The DispatcherServlet is a head waiter. Every slip goes to the head waiter first. The head waiter reads the path and the method and hands the slip to the right cook, which in Spring is a method in your controller:

@RestController public class HelloController { @PostMapping("/hello") public String hello(@RequestParam String uname) { return "Hello " + uname; } } 

So the journey in Spring Boot looks like this:

Request -> Tomcat -> DispatcherServlet -> your controller method

And now compare it to the Node if statements from Part 2. The DispatcherServlet is doing exactly that job, the if (req.url === ...), but in a smart, organized way. It reads the path, matches the verb, and calls the right method.

A controller is a servlet with a friendlier front desk.
That is why learning servlets first is worth it. When something breaks in Spring Boot, a 404, a 405, a missing parameter, the explanation almost always lives down in this layer.

Bonus fact: In a Spring Boot app you can register your own servlet next to the DispatcherServlet, as we did with @WebServlet. You need @ServletComponentScan on your main class so Spring Boot notices it. The more specific path (/firstServlet) wins over the catch-all /

Part 8: Try it yourself

Make your main class a plain Spring Boot starter:

@SpringBootApplication @ServletComponentScan public class StoreApplication { public static void main(String[] args) { SpringApplication.run(StoreApplication.class, args); } } 

Run it, then open Postman:

  • Method: POST
  • URL: http://localhost:8080/firstServlet
  • Body: x-www-form-urlencoded, with uname = Ade and ucity = Lagos

You should see:

Hello Ade
I know you're from Lagos

If you see Hello null, your body was not sent as x-www-form-urlencoded, or the key names do not match exactly. A quick way to check is to put the values in the URL instead: ?uname=Ade&ucity=Lagos.

Try sending a GET and watch the 405 appear. Then add a doGet method and watch it disappear. That small experiment teaches dispatching better than any diagram.

The whole story in one table
| Restaurant | Node | Java Servlets | Spring Boot |
| --- | --- | --- | --- |
| The building | http.createServer | Tomcat | Embedded Tomcat |
| The front door | server.listen(8080) | Tomcat's connector | Tomcat's connector |
| The paper slip | req | HttpServletRequest | HttpServletRequest |
| The plate | res | HttpServletResponse | return value / response |
| Reading the slip and choosing | your if statements | URL mapping + service() | DispatcherServlet |
| The cook | your callback | doGet / doPost | @GetMapping / @PostMapping method |

What to remember

  • A server is just a program that listens on a port, reads a request, and writes a response.
  • Node lets you build that program yourself. Java usually hands it to a container like Tomcat.
  • A servlet is the piece you write. The container calls it.
  • Dispatching is two lookups: path picks the servlet, HTTP verb picks the method.
  • Spring Boot adds a head waiter (DispatcherServlet) so you can write controllers instead of servlets.

Once you see the restaurant, no framework feels like magic anymore. It is the same restaurant with more helpful staff.

Have you built a server from scratch in Node or Java? Tell me in the comments what surprised you most.

原文:https://www.a8q9.cn/en/article/how-a-java-server-really-works-servlets-explained-2f8282.html

相关文章