JSTL的使用
jstl标签库,可以迭代查询到的集合显示到页面。
要使用jstl(Java standard taglib)需要下载开发包,可以到maven仓库下载
1.下载jstl的开发包(www.mvnrepository.com)
2.导入jstl的开发包
3.在控制层中定义查询集合的方法
public class EmpServlet extends BaseServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String pathInfo = req.getPathInfo();
if ("/add".equals(pathInfo)) {
this.addEmp(req, resp);
}else if ("/remove".equals(pathInfo)) {
this.removeEmp(req, resp);
}else if ("/get".equals(pathInfo)) {
this.getEmpById(req, resp);
}else if ("/list".equals(pathInfo)) {
this.getEmpList(req, resp);
}
}
/**
* 查询所有雇员的信息
* @param req
* @param resp
*/
public void getEmpList(HttpServletRequest req, HttpServletResponse resp) {
List<Emp> list = new ArrayList<>();
for (int i = 1; i <=10; i++) {
list.add(new Emp(100+i, "尼古拉斯"+i, "总裁", 50000.00, new Date(), 1, 10000.00, 10));
}
//将查询的数据保存到request内置对象
req.setAttribute("list", 10);
//跳转到emp_list.jsp页面显示数据
try {
req.getRequestDispatcher("/emp_list.jsp").forward(req, resp);
} catch (Exception e) {
e.printStackTrace();
}
}
将查询到的数据显示到JSP页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<c:forEach items="${list}" var="emp"> <!-- 对一个集合进行迭代 -->
<tr>
<td>${emp.empno}</td><td>${emp.ename}</td><td>${emp.job}</td><td>${emp.sal}</td>
<td>${emp.mgr}</td><td>${emp.hiredate}</td><td>${emp.comm}</td><td>${emp.deptno}</td>
</tr>
</c:forEach>
</body>
</html>
<c:forEach items="${list}" var=“emp”>
- items:指定要迭代的集合,使用EL表达式取得这个集合
- var=“temp”:将每次迭代到的数据保存到这个叫做temp的临时变量中