Table of contents
Open Table of contents
Article body
When including another JSP page, you need to understand <%include file=“***.jsp(no parameters may follow)”%> and <jsp:include page = “***.jsp” flush = “true”>: static and dynamic includes, respectively.
There are plenty of explanations of their differences online, but I tend to forget them shortly after reading. Here, I only want to remember one sentence:
With a static include, both JSP pages use the same servlet; with a dynamic include, each JSP has its own servlet.
Remembering that helps you avoid several pitfalls. For example:
-
With a static include, <%include file=“***.jsp”>, the two JSP pages must have matching <%page pageEncoding=“utf8”%> declarations, or an error occurs. The explanation above makes this easy to understand: what should a single servlet do with two different pageEncoding settings?
-
Statically included JSP pages cannot declare variables with the same name. The reason is the same: they compile into one servlet. If that servlet ends up with two identical variable declarations, the result is an error.
-
A static include produces a single class file. With dynamic includes, the number of class files corresponds to the number of JSP pages. Again, one servlet produces one class file, and N servlets produce N class files.
-
Looking more closely reveals further differences. Static includes are resolved before the servlet is compiled, whereas with dynamic includes, each servlet handles its own JSP. In the terminology used by online explanations, static inclusion happens during translation and dynamic inclusion during compilation.
One sentence lets us work out many of the differences, without repeatedly memorizing lists found online.