标准标签、<jsp:include>、<jsp:forward>

使用方法
  标准标签在jsp页面直接编写即可,因为标准标签是JSP规范提供的,所有容器都支持

被替代性
  标准标签的许多功能都可以被JSTL与EL表达式语言所替代

作用
  标准标签可协助编写JSP时减少Scriptlet的使用。

语法
  所有标准标签都使用jsp:作为前缀。


标准标签<jsp:include>

  和include指示元素对比:
  include指示元素,可以在JSP转译为Servlet时,将另一个JSP包括进来进行转译,这是静态地包括另一个JSP页面,也就是被包括的JSP与原JSP合并在一起,转译为一个Servlet类,你无法在运行时依条件动态地调整想要包括的JSP页面。
  <jsp:include>标签可以在运行时,依条件动态地调整想要包括的JSP页面,当前jsp会生成一个Servlet类,被包含的jsp也会生成一个Servlet类。

Demo

index.jsp

在index.jsp中使用了<jsp:param>标签,指定了传递给add.jsp的请求参数。

<%@page contentType="text/html" pageEncoding="UTF-8" %>
<jsp:include page="add.jsp">
    <jsp:param name="a" value="1"/>
    <jsp:param name="b" value="2"/>
</jsp:include>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
</body>
</html>
View Code

add.jsp

<%@page contentType="text/html" pageEncoding="UTF-8" isErrorPage="true" %>
<%@page import="java.io.PrintWriter" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>加法网页</title>
</head>
<body>
    <%
        String a = request.getParameter("a");
        String b = request.getParameter("b");
    %>
    <p>a + b = <%=a + b %></p>
</body>
</html>
View Code

测试地址:http://127.0.0.1/index.jsp

响应结果:a + b = 12

查看转译后的servlet

查看index_jsp.java的源码有如下代码:

      org.apache.jasper.runtime.JspRuntimeLibrary.include(
              request, 
              response, 
              "add.jsp" + "?" 
                      + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("a", request.getCharacterEncoding()) 
                      + "="
                      + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("1", request.getCharacterEncoding())
                      + "&" + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("b", request.getCharacterEncoding()) 
                      + "=" + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("2", request.getCharacterEncoding()), out, false);
View Code

上面的源码其实就是取得RequestDispatcher对象,并执行include()方法。


<jsp:forward>标签

  将请求转发给另一个JSP处理。
  同样地,当前页面会生成一个Servlet,而被转发的add.jsp也会生成一个Servlet。
  只要把上面index.jsp里的include改为forward即可。

查看index_jsp.java的源码有如下代码:

      if (true) {
        _jspx_page_context.forward("add.jsp" + "?" + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("a", request.getCharacterEncoding())+ "=" + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("1", request.getCharacterEncoding()) + "&" + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("b", request.getCharacterEncoding())+ "=" + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("2", request.getCharacterEncoding()));
        return;
      }
View Code

这里的源码其实就是取得RequestDispatcher对象,并执行forward()方法。

pageContext隐式对象具有forward()与include()方法。

原文地址:https://www.cnblogs.com/Mike_Chang/p/10082387.html