JSTL JSP Standard Tag Library 標准標簽庫
JSTL允許開人員可以像使用HTML標簽 那樣在JSP中開發Java功能。
JSTL庫有core, i18n, fmt, sql 等等。
public class SelectUserServlet extends HttpServlet {
SelectUser selectUser = new SelectUserImpl();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<User> userList = selectUser.selectList();
req.setAttribute("u",userList);
req.getRequestDispatcher("selectUserPage.jsp").forward(req,resp);
1.userList是從數據庫獲取的數據,是List的數據類型。
2.通過
req.setAttribute("u",userList);將后台數據綁定至 u
3.將數據轉發給顯示數據的前端jsp頁面。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>顯示用戶數據</title>
</head>
<style type="text/css">
td{
width: 90px;
}
</style>
<body>
<h1>用戶數據顯示</h1>
<table align='center' border='5' cellspacing='0'>
<tr>
<td>id</td>
<td>userName</td>
<td>userCode</td>
<td>userPassword</td>
<td>gender</td>
</tr>
<c:forEach items="${u}" var="user" varStatus="st">
<tr>
<td>${user.id}</td>
<td>${user.userName}</td>
<td>${user.userCode}</td>
<td>${user.userPassword}</td>
<td>${user.gender}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
4.前端頁面需要引入jstl標簽庫
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
5.通過
<c:forEach items="${u}" var="user" varStatus="st">
來遍歷查詢的數據。
| id | userName | userCode | userPassword | gender |
| 1 | admin | 系統管理員 | 1234567 | 1 |
| 2 | liming | 李明 | 0000000 | 2 |
| 5 | hanlubiao | 韓路彪 | 0000000 | 2 |
| 6 | zhanghua | 張華 | 0000000 | 1 |
| 7 | wangyang | 王洋 | 0000000 | 2 |
6.注意在獲取到后端頁面數據后,如果出現前端頁面報錯。如下面所示,去檢查jsp頁面的35行的數據,這個綁定數據必須與實體類的參數名稱一致。
private int id;
private String userCode;
private String userName;
private String userPassword;
private Integer gender;
如實體類寫的是
userPassword
但是jsp前端頁面如果寫的是
UserPassword 這樣會識別不出來!謹記
Type Exception Report
Message An exception occurred processing [/selectUserPage.jsp] at line [35]
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.apache.jasper.JasperException: An exception occurred processing [/selectUserPage.jsp] at line [35]
32: <td>${user.id}</td>
33: <td>${user.userName}</td>
34: <td>${user.userCode}</td>
35: <td>${user.UserPassword}</td>
36: <td>${user.Gender}</td>
37: </tr>
38:
