jsp:include 和 jsp:include

        期末考试的悲伤让我不想皮了这次……

        代码的可重用性是软件开发的一个重要原则。使用可宠用的组件可提高应用程序的生产率和可维护性。JSP规范定义了一些允许重用Web组件的机制,其中包含另一个Web组件的内容或者输出。这种可通过两种方式之一实现:静态包含或动态包含

       一、 静态包含:include指令

1、静态包含概述:

       静态包含数再JSP页面转换阶段将两一个文件的内容包含到当前JSP页面里。简单点说,就是把另一个文件全选然后复制粘贴到调用它的地方。

                           <%@ include file="relativeURL" %>

图解:

                  主页面main.jsp和被包含的页面other.jsp

2、从被包含页面中访问变量

        由于被包含JSP页面的代码成为主页面代码的一部分,所以,每个页面都可以访问在另一个页面中定义的变量。他们也共享所有的隐含变量。

//hello.jsp
<%@ page contentType="text/html;charset=utf-8" %>
<html>
<body>
<h1>My name is 哈哈哈哈哈士奇,What is your name??</h1>
<form action="" method=post>
	<input type="text" name="username" size=25">
	<input type="submit" value="提交">
	<input type="reset" value="重置">
</form>
<%! String userName="哈哈哈哈哈哈士奇"; %>
<%@ include file="response.jsp" %>
</body>
</html>

下面的代码是被包含页面的response.jsp

<%@ page contentType="text/html;charset=utf-8"%>
<% userName=request.getParameter("username"); %>
<h3> <font color="blue" >Hello,<%=userName %></font></h3>

     在hello.jsp页面中声明了一个变量userName,并使用include指令包含response.jsp页面,在response.jsp中使用了hello.jsp中生命的变量userName。程序运行结果如下(只运行hello.jsp就可以,我会讲为什么报错)

     二、动态包含:include动作

    动态包含是通过JSP标准动作<jsp:include>实现的。动态敖汉是在请求时将另一个页面的输出包含到主页面的输出中。

                                               <jsp:include page="relativeURL" flush="true|false"/>

   ps:page其值必须是相对URL

        flush属性是指在将控制转向被包含页面之前是否刷新主页面。如果当JSP页面被缓冲,那么在把输出流传递给被包含组件之前应该刷新缓冲区。flush默认为false。

图解:

page属性的值可以是请求时表达式

<%! String pageURL="other.jsp"' %>

<jsp: include page="<%=pageURL%>" /> 

1、使用<jsp:param>传递参数

      我们可以向被包含页面传递参数
 

 <jsp:include page="other.jsp">              
        <jsp:param name="name1" value="v1"/>            
        <jsp:param name="name2" value="<%= expression%>" />//还可以使用JSP表达式</jsp:include>

       通过<jsp:param>动作传递的“名/值”对保存在request对象中,丙炔只能由被包含的组件使用,再被包含的页面中使用request隐含对象的getParameter()获得传递来的参数。这些参数的作用域是被包含的页面,再被包含的组件完成粗粒后,容器将 从request对象中清除这些参数

2、与动态包含的组件共享对象

       被包含的页面时单独执行的,因此他们不能共享再主页面中定义的变量和方法。然而,他们处理的请求对象是相同,因此可以共享属于请求作用于的对象。

//hello.jsp
<%@ page contentType="text/html;charset=utf-8" %>
<html>
<body>
<h1>My name is 哈哈哈哈哈士奇,What is your name??</h1>
<form action="" method=post>
	<input type="text" name="username" size=25">
	<input type="submit" value="提交">
	<input type="reset" value="重置">
</form>
<%  String userName=request.getParameter("username");
    request.setAttribute("username",userName);
         %>
<%@ include file="response.jsp" %>
</body>
</html>
<%@ page contentType="text/html;charset=utf-8"%>
<% String userName=(String)request.getParameter("username"); %>
<h3> <font color="blue" >Hello,<%=userName %></font></h3>

ps:session ,application也是可以的

pssssss:想了解更多,可以 看我的   《静态包含的限制》、《<jsp:include>、<jsp:forward>的区别与等价语句结构》

 

发布了22 篇原创文章 · 获赞 2 · 访问量 5452

猜你喜欢

转载自blog.csdn.net/qq_43135849/article/details/91354379