JSP页面中include的两种方式

在JSP页面中,原生提供的include方法有两种:

  • include指令
<%@ include file="head.jsp" %>
  • <jsp:include>标签
<jsp:include path="head.jsp" />

使用include 指令

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
</head>
<body>
  <%@ include file="head.jsp" %>
  <h1>欢迎访问本站</h1>
</body>
</html>

include指令是静态包含,head.jsp页面里面的内容是被编译到index.jsp页面的service方法中的,运行速度快。
index.jsp页面中定义的变量在head.jsp中也是可以访问的。
include指令的file属性是不能使用变量值做热替换的,因为内容在编译时已经插入。

使用<jsp:include> 标签

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
</head>
<body>
  <jsp:include path="head.jsp" />
  <h1>欢迎访问本站</h1>
</body>
</html>

<jsp:include>标签是在运行时动态插入的,性能上有一定的开销。
index.jsp中定义的变量在head.jsp是不能访问的。
<jsp:include>标签的path属性是可以运行时的条件做热替换的。
例如: <jsp:include page="include/${param.page }.jsp"></jsp:include>

<jsp:include>标签的底层使用的是RequestDispatcher.include()方法

<%
out.flush();
String path = "head.jsp";
request.getRequestDispatcher(path).include(request, response);
%>

在include方法调用前,一定要调用out.flush()方法。
否则head.jsp的内会插入到当前页面(index.jsp)页面的最前面,<!DOCTYPE html>标签之前。

pageContext.include()方法也能实现相同的效果

<%
  pageContext.include("head.jsp");
%>

pageContext.include() 方法中已经调用了flush()方法,在当前页面不需要再调用out.flush()了。