为什么要用静态包含或动态包含
在开发的时候,我们有时候不会一整个界面就只用一个jsp文件来写,而是把它区分成几个模块,比如把商用的广告模块独立出来。
这样做的好处是什么呢?如果我们有一百个网站,某一天突然接到某个广告商需要打广告,如果我们所有的页面都是用一个jsp文件写的,那么我们就需要在这100个网站里面单独加这个模块。
但是,如果我们用包含的方式,把广告这个模块独立出来了,那么就只需要修改广告这一个小模块,其他地方不变。(如此,就算后期不做他的广告了,也可以只修改一个地方就把他的广告位去掉,省时省力)
大概就是这样,能不能听懂无所谓,下面直接讲解什么是jsp的静态包含和动态包含。
jsp的静态包含和动态包含
jsp的静态包含
其实说白了就是类似引入,把另一个jsp文件的布局啥的贴过来。
语法如下(/表示的是你的项目的webapp的子目录,或者有一些也叫web子目录):
<%@ include file="/你的jsp文件路径" @%>
举个例子:
在webapp的子目录下新建两个jsp文件,分别叫head.jsp和footer.jsp
head.jsp代码如下:
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2021/7/16
Time: 21:26
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>主页</title>
</head>
<body>
<h1>我是主页</h1>
<h2>我是主页的内容</h2>
<%@ include file="footer.jsp"%>
</body>
</html>
footer.jsp的代码如下:
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2021/7/16
Time: 21:26
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>底部广告位</title>
</head>
<body>
<h1>我是广告位</h1>
</body>
</html>
然后启动Tomcat服务器,进入工程下的head.jsp文件,可以看到底部的footer成功导入。
jsp的动态包含
语法:
<jsp:include\ page="/你的jsp文件路径"> <jsp:include>
他跟静态其实差不多,但是可以用jsp:param标签传参给引用的jsp文件。
修改一下上面两个文件:
head.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2021/7/16
Time: 21:26
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>主页</title>
</head>
<body>
<h1>我是主页</h1>
<h2>我是主页的内容</h2>
<%-- <%@ include file="footer.jsp"%>--%>
<jsp:include page="footer.jsp">
<jsp:param name="username" value="Keeling1720"/>
<jsp:param name="password" value="123456"/>
</jsp:include>
</body>
</html>
然后修改footer.jsp文件:
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2021/7/16
Time: 21:26
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>底部广告位</title>
</head>
<body>
<h1>我是广告位</h1>
<h2>username=<%=request.getParameter("username")%></h2>
<h2>password=<%=request.getParameter("password")%></h2>
</body>
</html>
刷新后,页面显示如下: