JSP的部分知识(二)

指令include和动作include的区别

通过之前的学习知道,JSP最后会被转译成Servlet
如果是指令include

<%@include file="footer.jsp" %>

footer.jsp的内容会被插入到 hello.jsp 转译 成的hello_jsp.java中,最后只会生成一个hello_jsp.java文件
如果是动作include

<jsp:include page="footer.jsp" />

footer.jsp的内容不会被插入到 hello.jsp 转译 成的hello_jsp.java中,还会有一个footer_jsp.java独立存在。 hello_jsp.java 会在服务端访问footer_jsp.java,然后把返回的结果,嵌入到响应中。

传参

因为指令<%@include 会导致两个jsp合并成为同一个java文件,所以就不存在传参的问题,在发出hello.jsp 里定义的变量,直接可以在footer.jsp中访问。
而动作<jsp:include />其实是对footer.jsp进行了一次独立的访问,那么就有传参的需要。

如本例:
1. 在hello.jsp中使用动作<jsp:include,并通过<jsp:param 带上参数

<jsp:include page="footer.jsp">
    <jsp:param  name="year" value="2017" />
</jsp:include>

2. 在footer.jsp中,使用request.getParameter("year")取出year

(hello.jsp代码)

<%@page contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*"%>
  。。。(省略)
你好 JSP
<%=new Date().toLocaleString()%>
 
<jsp:include page="footer.jsp">
    <jsp:param  name="year" value="2017" />
</jsp:include>

(footer.jsp代码)

<hr>
    <p style="text-align:center">copyright@<%=request.getParameter("year")%>
</p>

和Servlet的跳转一样,JSP的跳转也分服务端跳转(转发)和客户端跳转(重定向)。

首先准备 jump.jsp

首先准备一个jump.jsp 来分别演示客户端跳转和服务端跳转。

客户端跳转

jsp的客户端跳转和Servlet中是一样的。

response.sendRedirect("hello.jsp");

可以通过firefox的调试工具可以观察到访问jump.jsp返回302(临时客户端跳转),跳转到了hello.jsp

JSP的部分知识(二)

<% 
    response.sendRedirect("hello.jsp");
%>

服务端跳转

与Servlet的服务端跳转一样,也可以使用

request.getRequestDispatcher("hello.jsp").forward(request, response);

或者使用动作,简化代码

<jsp:forward page="hello.jsp"/>

JSP的部分知识(二)

原文地址:http://how2j.cn/k/jsp/jsp-tutorials/530.html