我得到一个类似的 JSON 数组:
[com.core.newbie.controller.UserController](信息来自):[{"age":24,"id":1,"password":"001","userName":"001"},{"age":24,"id":2,"password":"002","userName":"002"},{"age":24,"id":3,"password":"002","userName":"002"},{"age":24,"id":4,"password":"004","userName":"004"},{"age":24,"id":5,"password":"005","userName":"005"},{"age":14,"id":111,"password":"12","userName":"derrick-2"}]
UserController,右侧代码:
@RequestMapping("/users")
public String users(final Model model) {
final List<User> users = userService.getAll();
model.addAttribute("users", users);
logger.debug("running in UserController.java -> users()");
logger.info(JSON.toJSON(users));
return "/user/users.jsp";
}
我正在尝试在 users.jsp 中显示它:
Пользователи:
=<c:forEach begin="0" end="${users.length() -1}" var="user" items="${users}">
<div>
${user.userName}
</div>
<br />
</c:forEach>
但它不输出。
$(users) 输出:
[com.core.newbie.model.User@5fc33319, com.core.newbie.model.User@6a8d7cfc, com.core.newbie.model.User@708bb2c2, com.core.newbie.model.User@500e9d80, com.core.newbie.model.User@16133763, com.core.newbie.model.User@1778c3c1]
同时,在通常的 User (1) 的情况下,一切都正确显示,来自 UserController 的代码:
@RequestMapping("/showUser")
public String showUser(final HttpServletRequest request, final Model model)
{
final int userId = Integer.parseInt(request.getParameter("id"));
final User user = userService.getUserById(userId);
model.addAttribute("user", user);
logger.debug("running in UserController.java -> showUser()");
logger.info(JSON.toJSON(request.getRequestURI()));
logger.info(JSON.toJSON(user));
return "/user/showUser.jsp";
}
UPD:UserServiceImpl.java,获取列表的一部分:
@Override
@Select("select * from n_user")
public List<User> getAll() {
return userMapper.findAll();
}
UPD2:编辑后代码变成了这样:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Пользователи</title>
</head>
<body>
Пользователи:
<c:forEach var="user" items="${users}">
<div>
<c:out value="${user.userName}" />
</div>
<br />
</c:forEach>
</body>
</html>
页面上仅显示“用户:”一词。${user.id} 和 ${user} 都不会在循环中输出任何内容。
首先,你没有得到 JSON,而是一个常规的
User
. 在 JSON 中,您仅在输出到日志时将其转换,并以其原始形式进入 JSP 页面。其次,列表元素的迭代变得更容易:该类
User
必须有一个 gettergetUserName
。原来需要在jsp中包含如下代码: