一、jsp 静态包含
<%@ include file="/include/footer.jsp"%>
静态包含的特点:
- 静态包含不会翻译被包含的 jsp 页面。
- 静态包含其实是把被包含的 jsp 页面的代码拷贝到包含的位置执行输出。
二、jsp 动态包含
动态包含也可以像静态包含一样,把被包含的内容执行输出到包含位置。page
属性是指定你要包含的 jsp
页面的路径。
<jsp:include page="/include/footer.jsp">
<jsp:param name="username" value="bbj"/>
<jsp:param name="password" value="root"/>
</jsp:include>
动态包含的特点:
- 动态包含会把包含的 jsp 页面也翻译成为 java 代码
- 动态包含底层代码使用如下代码去调用被包含的 jsp 页面执行输出
JspRuntimeLibrary.include(request, response, "/include/footer.jsp", out, false);
- 动态包含,还可以传递参数
动态包含的底层原理:共用一个out
缓冲区
三、jsp 标签-转发
/*
<%
request.getRequestDispatcher("/scope1.jsp").forward(request,response);
%>
*/
<jsp:forward page="/scope1.jsp"></jsp:forward>
SearchStudentServlet
类
public class SearchStudentServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取请求的参数
//发sql语句查询学生的信息
//使用for循环生成查询到的数据做模拟
List<Student> studentList = new ArrayList<Student>();
for (int i = 0; i < 10; i++) {
int t = i + 1;
studentList.add(new Student(t, "name" + t, 18 + t, "phone" + t));
}
//保存查询到的结果到request域中
request.setAttribute("stuList",studentList);
//请求转发到showStudent.jsp页面
request.getRequestDispatcher("/showStudent.jsp").forward(request,response);
}
}
showStudent.jsp
<body> <%--练习二:jsp 输出一个表格,里面有 10 个学生信息。--%>
<% List<Student> studentList = (List<Student>) request.getAttribute("stuList"); %>
<table>
<tr>
<td>编号</td>
<td>姓名</td>
<td>年龄</td>
<td>电话</td>
<td>操作</td>
</tr>
<% for (Student student : studentList) { %>
<tr>
<td><%=student.getId()%>
</td>
<td><%=student.getName()%>
</td>
<td><%=student.getAge()%>
</td>
<td><%=student.getPhone()%>
</td>
<td>删除、修改</td>
</tr>
<% } %></table>
</body>