Servlet 教程

Servlet 是什么、它在 Java Web 里的位置,以及一门课走完的学习路线。

Beginner
Key PointsServlet 是运行在服务端容器里的 Java 类,负责接收 HTTP 请求并生成响应;容器负责生命周期、线程与协议解析。

Servlet 是什么

A servlet is a server-side component defined by the Java EE spec. It does not listen on a port or parse HTTP — the servlet container (Tomcat, Jetty, Undertow) does. The container wraps the request into HttpServletRequest and the response writer into HttpServletResponse, then hands both to your service() method.

它在 Web 应用中的位置

LayerJob
Browser发 HTTP 请求、渲染 HTML
Web server / container监听端口、解析协议、管理 Servlet 生命周期
Servlet读参数、做业务、写响应
Business / DAO真正的领域逻辑与数据访问

Early servlets printed HTML with out.println("<html>..."), mixing markup and Java so that every tag change required a recompile. Later the page-rendering job moved to JSP and servlets retreated to the controller role — that is where MVC starts.

第一个 Servlet 长什么样

Java
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = resp.getWriter()) {
            out.println("<!DOCTYPE html>");
            out.println("<h1>Hello, Servlet</h1>");
        }
    }
}

@WebServlet("/hello") maps /hello to this class, so no web.xml is needed. Extending HttpServlet lets the container dispatch by HTTP method to doGet / doPost, so you never inspect request.getMethod() yourself.

Since Jakarta EE 9 the package is jakarta.servlet instead of javax.servlet. Tomcat 10+ uses jakarta, Tomcat 9 and earlier still use javax. The import must match the container version or you get ClassNotFoundException.

学习路线

  1. 环境与生命周期 —— 容器做了什么、init/service/destroy 何时调用
  2. 请求与响应 —— 参数、头、Cookie、状态码、重定向
  3. 会话与状态 —— Cookie、Session、URL 重写
  4. 横切能力 —— 过滤器、异常处理、国际化
  5. 实战 —— 上传、数据库、发邮件、打包部署

Friends & Partners