JSP 生命周期

翻译、编译、初始化、服务、销毁五个阶段,以及 jspInit / jspDestroy。

Beginner
Key PointsJSP 首次访问时被翻译成 Servlet 再编译,之后与 Servlet 生命周期完全一致。

五个阶段

StageWhat happensCount
Translation.jsp → _jsp.java首次或文件改动后
Compilation_jsp.java → .class同上
InitialisationjspInit()1
Service_jspService()每个请求
DestructionjspDestroy()1

翻译出来的类

Java
public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase {
    // 你在 JSP 里声明的 <%! %> 成员会变成类的字段
    public void _jspInit() { }
    public void _jspDestroy() { }

    public void _jspService(HttpServletRequest request,
                            HttpServletResponse response) {
        // 隐式对象在这里被赋值
        // 你的 HTML 变成 out.write("...")
        // 你的 <% %> 变成普通语句
        // 你的 <%= %> 变成 out.print(...)
    }
}

That is why request, session and out are available in a JSP: they are local variables of _jspService, assigned by the container at the top of the method.

jspInit 与 jspDestroy

JSP
<%!
    private java.time.LocalDateTime startedAt;

    @Override
    public void jspInit() {
        startedAt = java.time.LocalDateTime.now();
        getServletContext().log("页面已初始化");
    }

    @Override
    public void jspDestroy() {
        getServletContext().log("页面已销毁");
    }
%>

<p>本页面初始化于:<%= startedAt %></p>

<%! %> declares class members, initialised once and shared by every request — fine for config, constants and read-only references, never for per-request data.

A JSP is single-instance and multi-threaded too. A mutable field in <%! %> is a concurrency bug by construction; int counter plus <% counter++ %> is the classic bad example.

首次访问为什么慢

The first request pays translation, compilation and class loading — hundreds of milliseconds to seconds; later requests hit the cache. To avoid a slow first visit, precompile via jsp-config in web.xml or the JSPC tool at build time.

XML
<jsp-config>
  <jsp-property-group>
    <url-pattern>*.jsp</url-pattern>
    <page-encoding>UTF-8</page-encoding>
    <trim-directive-whitespaces>true</trim-directive-whitespaces>
  </jsp-property-group>
</jsp-config>

Friends & Partners