您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
14-Spring练习-用户列表展示2(子循环)
发布时间:2025-01-08 21:17:03编辑:雪饮阅读()
-
在上篇中用户列表虽然已完成,但是用户所属角色列表没有完成,这里就继续完成用户列表的子列表即每个用户的角色列表。
那么开始之前再分享一个小技巧,如果你要写java里面的foreach循环,即类似这样
for (User user:userList) {
}
可以直接在IntelliJ IDEA中输入fo然后就会有提示了,可能你输入f都会有提示,在提示里面光标选中foreach然后回车即可快速创建该结构,然后自己填充下左边部分的每个循序item的类型及变量名,以及右边被循环的变量

那么我们继续查询每个用户的角色列表,则需要关联表的数据。
CREATE TABLE `sys_user_role` (
`userId` bigint(20) NOT NULL,
`roleId` bigint(20) NOT NULL,
PRIMARY KEY (`userId`,`roleId`),
KEY `roleId` (`roleId`),
CONSTRAINT `sys_user_role_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `sys_user` (`id`),
CONSTRAINT `sys_user_role_ibfk_2` FOREIGN KEY (`roleId`) REFERENCES `sys_role` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*Data for the table `sys_user_role` */
insert into `sys_user_role`(`userId`,`roleId`) values (1,1),(1,2),(2,2),(2,3);
那么接下来我们需要为userService的实现类里面将每个user的roles实现出来,而roles应该归分给roleDao去实现更合适,所以我们的UserServiceImpl实现类如:
package sp21.service.impl;
import sp21.dao.RoleDao;
import sp21.dao.UserDao;
import sp21.domain.Role;
import sp21.domain.User;
import sp21.service.UserService;
import java.util.List;
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
private RoleDao roleDao;
public void setRoleDao(RoleDao roleDao) {
this.roleDao = roleDao;
}
public List<User> list() {
List<User> userList=userDao.findAll();
for (User user:userList) {
Long id=user.getId();
List<Role> roles=roleDao.findRoleByUserId(id);
user.setRoles(roles);
}
return userList;
}
}
这里既然用到了roleDao,那么所以在Spring Config配置文件中需要也给userService注入
<!--配置userService-->
<bean id="userService" class="sp21.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"/>
<property name="roleDao" ref="roleDao"/>
</bean>
然后由于需要用到roleDao去按用户id获取该用户的roles,所以roleDao接口也调整下
新增抽象方法
List<Role> findRoleByUserId(Long id);
然后RoleDaoImpl实现类进一步实现该抽象方法
public List<Role> findRoleByUserId(Long id) {
List<Role> roles = jdbcTemplate.query("select r.* from sys_user_role ur,sys_role r where ur.roleId=r.id and userId=?", new BeanPropertyRowMapper<Role>(Role.class),id);
return roles;
}
然后pages/user-list.jsp中上次没有完善的每个用户的角色列表重新完善如:
<c:forEach items="${userList}" var="user">
<tr>
<td><input name="ids" type="checkbox"></td>
<td>${user.id}</td>
<td>${user.username}</td>
<td>${user.email}</td>
<td>${user.phoneNum}</td>
<td class="text-center">
<c:forEach items="${user.roles}" var="role">
${role.roleName}
</c:forEach>
</td>
<td class="text-center">
<a href="javascript:void(0);" class="btn bg-olive btn-xs">删除</a>
</td>
</tr>
</c:forEach>
这里的子循环就是完善了每个用户的角色列表。
关键字词:Spring,用户列表,子循环