JSP 简介

JSP 的优势、与纯 Servlet 和静态 HTML 的对比、适合与不适合的场景。

Beginner
Key PointsJSP 适合以「页面」为中心的应用;纯前后端分离的 API 项目不需要它。

相比纯 Servlet 的好处

  • 写页面像写 HTML —— 不用为每个标签写 out.println
  • 改页面不用重编译 —— 改 .jsp 后容器自动重新翻译
  • 内置对象 —— request、session、out 直接可用
  • 标签库 —— JSTL 提供循环、条件、格式化,不用写 Java

和静态 HTML 的差别

JSP
Content固定不变按请求、用户、数据变化
Served byWeb 服务器直接读文件容器执行后生成 HTML
Cost一次磁盘读一次翻译 + 编译(仅首次)+ 每次执行

适合的场景

  • 服务端渲染的后台管理界面 —— 表单多、权限多、交互简单
  • 以内容为主的站点 —— 新闻、文档、电商列表页,SEO 友好
  • 老系统维护 —— 大量存量 JSP,改造成本高于维护成本

不适合的场景

Pure API services, interaction-heavy single-page apps, and UIs needing frequent partial updates all fight against JSP. Return JSON for the first, let a frontend framework handle the second, and keep the server to endpoints.

JSP is not obsolete, its niche just narrowed. Modern stacks use Thymeleaf, Freemarker or a frontend framework, but understanding how JSP is translated explains why every template engine warns against business logic in the view.

页面里的四种元素

JSP
<%-- 1. 注释:不会出现在响应里 --%>

<%-- 2. 指令:告诉容器怎么处理这个页面 --%>
<%@ page contentType="text/html;charset=UTF-8" %>

<%-- 3. 脚本片段:任意 Java 语句 --%>
<% int n = 3; %>

<%-- 4. 表达式:输出一个值,不要加分号 --%>
<p>n 的平方是 <%= n * n %></p>
Output
n 的平方是 9

Friends & Partners