为什么JSP仅显示单个员工详情而非全部?附Servlet-JSTL代码场景
嘿,我帮你把这段展示员工详情的代码用规范的Markdown格式整理好了,这样看起来更清晰,也方便后续使用:
Servlet 代码实现
这部分是你用来从数据库获取员工数据、封装成列表并转发到JSP的核心逻辑:
// 先创建Employee对象的ArrayList并填充数据(这里省略数据库查询逻辑) ArrayList<Employee> list = new ArrayList<>(); // 假设你已经通过数据库操作把员工数据填充到list里了 // 将员工列表设置为请求属性,键为"emp" request.setAttribute("emp", list); // 获取请求转发器,指定要跳转的JSP页面 RequestDispatcher rd = request.getRequestDispatcher("/rafi.jsp"); // 执行转发操作,把请求和响应对象传递过去 rd.forward(request, response);
JSP 页面(使用JSTL展示员工详情)
要在JSP里顺利遍历员工列表,记得先引入JSTL核心标签库,然后用<c:forEach>标签循环展示每个员工的信息:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>员工详情列表</title> <style> table { border-collapse: collapse; margin: 20px 0; } th, td { border: 1px solid #ccc; padding: 8px 12px; text-align: left; } th { background-color: #f5f5f5; } </style> </head> <body> <h2>员工详情列表</h2> <table> <tr> <th>员工ID</th> <th>姓名</th> <th>职位</th> <th>薪资</th> <!-- 可以根据你的Employee类属性添加更多列哦 --> </tr> <!-- 遍历请求属性中名为"emp"的列表,每次循环把当前员工对象赋值给employee变量 --> <c:forEach var="employee" items="${emp}"> <tr> <td>${employee.id}</td> <td>${employee.name}</td> <td>${employee.position}</td> <td>${employee.salary}</td> <!-- 替换成你Employee类里的实际属性名 --> </tr> </c:forEach> </table> </body> </html>
内容的提问来源于stack exchange,提问作者Arfa Rumana
相关产品推荐
相关产品推荐

