java查询的数据返回给jsp页面,通过jstl来获取后端页面数据,并显示数据

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: 
 


posted @ 2022-04-18 13:43  LoveYouLoveMe  阅读(2144)  评论(0编辑  收藏  举报