JSP 教程

JSP 是什么、它和 Servlet 的分工,以及一门课的学习路线。

Beginner
Key PointsJSP 最终会被容器翻译成 Servlet:写页面用 JSP,做控制用 Servlet,两者是同一套机制的两张脸。

JSP 是什么

JSP (JavaServer Pages) is a page technology that embeds Java in HTML. It frees the view layer from printing tags with out.println; you write HTML directly and drop in a scriptlet or expression only where content is dynamic.

它其实是 Servlet

On first access the container translates the .jsp into .java, compiles it, and runs it as a servlet. Every JSP behaviour — lifecycle, implicit objects, threading — comes straight from the servlet spec.

Text
index.jsp
   ↓ 翻译(首次访问时)
index_jsp.java        → 一个 HttpServlet 子类
   ↓ 编译
index_jsp.class
   ↓ 容器加载
_jspService(request, response)   ← 你的 HTML 与脚本都进了这个方法

JSP 与 Servlet 的分工

JSP
Good at控制流程、调业务、选视图呈现 HTML
Awkward at拼大段 HTML写复杂业务逻辑
Role in MVCControllerView
Testing容易单测难,需要容器

第一个 JSP

JSP
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page import="java.time.LocalDateTime" %>
<!DOCTYPE html>
<html>
<head><title>第一个 JSP</title></head>
<body>
  <h1>你好,JSP</h1>
  <p>服务器时间:<%= LocalDateTime.now() %></p>
  <p>1 + 2 = <%= 1 + 2 %></p>
</body>
</html>
Output
你好,JSP
服务器时间:2026-11-03T14:25:09.418
1 + 2 = 3
Almost every JSP needs <%@ page contentType="text/html;charset=UTF-8" %>. Without it the container defaults to ISO-8859-1 and Chinese text turns into question marks.

学习路线

  1. 语法与指令 —— page、include、taglib,脚本元素与表达式
  2. 隐式对象 —— request、response、session、application、out
  3. EL 与 JSTL —— 用标签代替脚本,页面里不出现 Java 代码
  4. JavaBean 与自定义标签 —— 把逻辑从页面搬走
  5. 实战 —— 数据库、XML、上传、国际化、异常页

Friends & Partners