servlet和JSP单独使用的话,一般是servlet拿着客户数据直接用PrintWrite()输出,JSP嵌入java代码输出。这两种方法都很不方便。
servlet和JSP混合使用
request.setAttribute("customers",customers);
servlet中放数据
将客户数据塞到request里面
将customer数据传递给JSP(通过转发),JSP拿到数据后,拼接HTML然后输出给客服端。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取客户数据c
List<Customer> customers=Date.getCustomers();
//将客户数据存储到request中
request.setAttribute("customers",customers);
//转发到list.jsp页面进行数据展示
request.getRequestDispatcher("/page/list.jsp").forward(request,response);
}
当在浏览器输入访问list这个servlet后,会自动跳转到list.jsp。转发有点像跳转,但他们的数据是共享的。
JSP中拿数据
<%
List<Customer> customers= (List<Customer>) request.getAttribute("customers");
%>
目标:servlet总不要一句html代码,jsp中不要一句java代码
EL表达式,标签库
可以简化java代码,使jsp中不用任何java代码
下载标签库.
下载jar包后,导入步骤:
1.在WEB_INF下新建文件夹lib,所有jar包都放在lib文件夹中
2.选中导入的jar包,右击–>Add as library,level选Module
3.添加标签:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
//设置标签库名:C 因为不止一个标签库。类似命名空间
<%-- ${customers}" 就相当于 request.getAttribute("customers") --%>
<c:forEach items="${customers}" var="customer">
<tr>
<%--
name是private的,所以这里是寻找属性名而不是成员变量。所以这里的.name是去找getname()方法。
--%>
<td>${customer.name}</td>
<td>${customer.age}</td>
<td>${customer.height}</td>
</tr>
</c:forEach>
转发
重定向
在SaveServlet下,存储完数据需要调用ListServlet进行显示。如果是转发,地址栏URL不改变:服务器并没有发送响应给客户端,客户端不知道服务器的具体走向。
此时需要用到重定向
/*转发
request.getRequestDispatcher("/list").forward(request,response);
转发,列表展示地址栏格式是/save,不对,应该是/list
*/
//页面重定向
response.sendRedirect("/crm/list");
//可以写response.sendRedirect("http://www.baidu.com");
// 但是如果没有告诉域名,就认为在此服务器中重定向,所以在http://localhost:8080后拼接