【发布时间】:2020-01-24 10:15:54
【问题描述】:
我在带有 JSP 的 Spring Boot 2 中有一个简单的 Java 应用程序。 我使用 h2 数据库来测试数据。 它工作正常,但 JSP 不呈现来自控制器的列表数据。 JSP 中的列表是空的,而在控制器中它有 2 个值。 String 等其他属性工作正常。 我不明白问题出在哪里。
控制器:
@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";
}
}
用户模型:
@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 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" />
从控制器调试:
user: User(id=111111, firstName=Wick, lastName=England, country=John)
user: User(id=111112, firstName=Madman, lastName=USA, country=Andy)
UserService.cls 从 h2 返回 List 并且它在调试中,它 看起来不错。
@Transactional
public List<User> getAll() {
return (List<User>) this.userRepository.findAll();
}
截图:
【问题讨论】:
-
jsp文件中不包含用户模型类。
-
@reporter 好点,我添加了导入但行为是相同的。 表还是空的。
-
@ArvindKumarAvinash JSP 名称为 users,与属性名称“users”相同。
-
我不确定,但你能不能替换这部分:`map.addAttribute("users", this.userService.getAll());` 用删除一个列表并在你的模型中分配该列表喜欢你这里的吗?
-
@user404 我已经尝试过了,但它没有帮助;(我什至创建了具有相同属性的内部 tmp 类并将其添加到列表中以摆脱 User.cls 关系,但它没有帮助...
标签: java spring-boot jsp