JSP 指令

page、include、taglib 三个指令的属性与常见用法。

Beginner
Key Pointspage 指令设页面属性,include 静态合并文件,taglib 引入标签库前缀。

page 指令

JSP
<%@ page contentType="text/html;charset=UTF-8"
         pageEncoding="UTF-8"
         import="java.util.*, java.time.LocalDate"
         session="true"
         errorPage="/WEB-INF/errors/500.jsp"
         isErrorPage="false"
         buffer="8kb"
         autoFlush="true"
         isELIgnored="false"
         trimDirectiveWhitespaces="true" %>
AttributeMeaning
contentType响应的 MIME 与字符集,决定浏览器怎么解析
pageEncodingJSP 源文件本身的编码,决定容器怎么读文件
import唯一可以在同一页多次出现的属性
sessionfalse 时不创建 session,session 隐式对象不可用
errorPage本页抛异常时转到哪里
isErrorPagetrue 时可用 exception 隐式对象
buffer / autoFlush输出缓冲大小与满时是否自动刷新
pageEncoding tells the container how to read the file; the charset in contentType tells the browser how to read the response. Setting both to UTF-8 is the safe move — setting only one eventually garbles something.

include 指令

JSP
<%@ include file="/WEB-INF/parts/header.jsp" %>

Static include pastes the target file in at translation time, merging both into one servlet. The included file must not repeat <!DOCTYPE>/<html> and should not declare conflicting page attributes.

taglib 指令

JSP
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<%@ taglib prefix="fmt" uri="jakarta.tags.fmt" %>
<%@ taglib prefix="fn" uri="jakarta.tags.functions" %>

<c:forEach var="u" items="${users}">
  <p><c:out value="${u.name}"/> — <fmt:formatDate value="${u.created}" pattern="yyyy-MM-dd"/></p>
</c:forEach>

prefix is your page-local alias; uri must match the TLD. JSTL 1.x uses http://java.sun.com/jsp/jstl/core, JSTL 2.0+ (Jakarta) uses jakarta.tags.core.

一个完整的页面头

JSP
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import="com.example.model.User" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<%@ taglib prefix="fmt" uri="jakarta.tags.fmt" %>
<%-- 到这里为止都不产生任何输出 --%>
<!DOCTYPE html>
<html lang="zh-CN">

Keep directives at the top: they emit nothing, but appearing after HTML puts stray blank lines in the body and can even trigger IllegalStateException once the response is committed.

Friends & Partners