gpt4 book ai didi

java - JSP 在 Spring Boot 2 中不渲染 java 列表

转载 作者:行者123 更新时间:2023-12-02 09:04:56 25 4
gpt4 key购买 nike

我在 Spring Boot 2 中有一个带有 JSP 的简单 java 应用程序。我使用h2数据库来测试数据。它工作正常,但 JSP 不会呈现来自 Controller 的列表数据。JSP 中的列表是空的,而在 Controller 中它有 2 个值。其他属性(例如 String)工作正常。我不明白问题出在哪里。

Controller:

@Controller
public class HomeController {

@Autowired
UserService userService;

@GetMapping("/users")
public String getUsers(ModelMap map) {
this.userService.getAll().forEach(user -> System.out.println("user: " + user));
map.addAttribute("users", this.userService.getAll());
return "/users";
}
}

User model:

@NoArgsConstructor
@Getter
@Setter
@EqualsAndHashCode
@ToString
@Entity
public class User implements Serializable {

@Id
@GeneratedValue
private Long id;
private String firstName;
private String lastName;
private String country;

public User(@JsonProperty Long id, @JsonProperty String firstName, @JsonProperty String lastName, @JsonProperty String country) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.country = country;
}
}

JSP page:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<jsp:include page="header.jsp">
<jsp:param name="title" value="LIBRARY - Users"/>
</jsp:include>
<!--NAVBAR-->
<%@ include file="navbar.jsp"%>
<!--CONTENT-->
<div class="container-fluid h-100">
<table class="table table-hover">
<thead>
<tr>
<th>Index</th>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<c:forEach items="${users}" var="user" varStatus="iteration">
<tr>
<td>${iteration.index}</td>
<td>${user.id}</td>
<td>${user.firstName}</td>
<td>${user.lastName}</td>
<td>${user.country}</td>
</tr>
</c:forEach>
</tbody>
</table>
<c:if test="${empty users}">
<div class="d-flex justify-content-center">
<p>There are no records in the database</p>
</div>
</c:if>
</div>
<jsp:include page="footer.jsp" />

Debug from the controller:

user: User(id=111111, firstName=Wick, lastName=England, country=John)
user: User(id=111112, firstName=Madman, lastName=USA, country=Andy)

UserService.cls returns List from h2 and it is in the debug, it looks fine.

@Transactional
public List<User> getAll() {
return (List<User>) this.userRepository.findAll();
}

Screenshot:

enter image description here这里可能出现什么问题?

最佳答案

在 JSP 顶部添加以下行:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

另外,替换

return "/users";

return "users";

关于java - JSP 在 Spring Boot 2 中不渲染 java 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59894386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com