建议配合视频学习食用(10-1):
https://www.bilibili.com/video/BV1rr4y1F7Y2?p=1
20.3.2 登录
20.3.2.1 实体类
Account.java新加
//角色列表
private List<AccountRole> roleList;
AccountRole.java
package com.manong.entity;
import lombok.Data;
@Data
public class AccountRole {
private Integer id;//角色编号
private String roleCode;//角色编码
private String roleName;//角色名称
private String roleDesc;//角色描述
}
20.3.2.2 数据层
AccountRoleMapper.java
package com.manong.dao;
import com.manong.entity.AccountRole;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface AccountRoleMapper {
/**
* 根据用户ID查询该用户的角色列表
* @param accountId
* @return
*/
@Select("select * from t_role where id in(select roleId from t_account_role where accountId=#{accountId})")
List<AccountRole> findRoleListByAccountId(Integer accountId);
/**
* 添加角色关系
* @param accountId
*/
@Insert("insert into t_account_role (accountId,roleId) values(#{accountId},1)")
void insertAccountRole(Long accountId);
}
用户有了角色,findAccountByName对应的xml文件需要修改
AccountMapper.xml
<!-- 定义用户角色关系关联 -->
<resultMap id="accountRoleResultMap" type="com.manong.entity.Account" extends="BaseResultMap">
<!-- 一对多 -->
<collection property="roleList" ofType="com.manong.entity.AccountRole" column="id"
select="com.manong.dao.AccountRoleMapper.findRoleListByAccountId"/>
</resultMap>
<select id="findAccountByName" resultMap="accountRoleResultMap">
select * from t_account where loginName = #{loginName}
</select>
20.3.2.3 业务层
AccountService.java
AccountServiceImpl.java
/**
* 根据用户名查询用户信息
* @param username
* @return
* @throws UsernameNotFoundException
*/
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//创建角色列表集合
List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
//调用根据用户名查询用户信息的方法
Account account = accountMapper.findAccountByName(username);
//循环遍历角色列表
for (AccountRole accountRole : account.getRoleList()) {
authorities.add(new SimpleGrantedAuthority(accountRole.getRoleCode()));
}
//创建User对象
User user = new User(account.getLoginName(),account.getPassword(),
account.getStatus()==1,
true,
true,
true,
authorities);
return user;
}
每个注册用户都自动获得一个注册角色,修改addAccount方法
@Resource
private AccountRoleMapper accountRoleMapper;
public int addAccount(Account account) {
account.setRegistTime(new Date());//注册时间
account.setPassword(PasswordUtil.encode(account.getPassword()));//密码
account.setStatus(1);//可用
int count = accountMapper.addAccount(account);
if(count>0){
//添加角色关系
accountRoleMapper.insertAccountRole(account.getId());
}
return count;
}
20.3.2.4 配置文件
hotel-web下的spring-security.xml
20.3.4.5 新建welcome.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>酒店首页</title>
</head>
<body>
<script>
location.href="/index.jsp";
</script>
</body>
</html>