一、课程目标 1. 【掌握】角色管理功能 2. 【掌握】用户管理功能 二、角色管理 2.1 查询角色 编写RoleMapper接口 //查询所有角色 @Select ( "select * from role" ) public List Role selectAll (); 编写Rol
一、课程目标
1. 【掌握】角色管理功能2. 【掌握】用户管理功能
二、角色管理
2.1 查询角色
编写RoleMapper接口
//查询所有角色@Select("select * from role")
public List<Role> selectAll();
编写RoleService
public interface RoleService {//查询所有角色
public List<Role> findAll();
}@Service("roleService")
public class RoleServiceImpl implements RoleService {
@Autowired
RoleMapper roleMapper;
@Override
public List<Role> findAll() {
return roleMapper.selectAll();
}
}
编写RoleController
@Controller@RequestMapping("/role")
public class RoleController {
@Autowired
RoleService roleService;
/*
* 查询所有数据
* param request page limit
* */
@RequestMapping("/findAll")
public String findAll(HttpServletRequest request, @RequestParam(value = "page",required = false,defaultValue = "1") int page, @RequestParam(value = "limit",required = false,defaultValue = "5")int limit){
PageHelper.startPage(page,limit);
List<Role> all = roleService.findAll();
PageInfo<Role> pageInfo=new PageInfo<>(all);
request.setAttribute("pageInfo",pageInfo);
return "/role/role-list";
}
}
测试
2.2 角色添加
编写RoleMapper接口
//添加角色信息@Insert("insert into role(roleName,roleDesc)values(#{roleName},#{roleDesc})")
public int insert(Role role);
编写RoleService
//添加角色信息public int add(Role role);@Override
public int add(Role role) {
return roleMapper.insert(role);
}
编写RoleController
@RequestMapping(value = "/add",method = RequestMethod.GET)public String toAdd(){
return "/role/role-add";
}
@RequestMapping(value = "/add",method = RequestMethod.POST)
public String add(Role role){
roleService.add(role);
return "redirect:/role/findAll";
}
测试
2.3 角色修改
编写RoleMapper接口
//根据角色id查询角色信息@Select("select * from role where id=#{id}")
public Role selectById(int id);
//修改角色信息
@Update("update role set roleName=#{roleName},roleDesc=#{roleDesc} where id=#{id}")
public int update(Role role);
//查询角色权限管理表中当前角色拥有的权限id集合
@Select("select permissionId from role_permission where roleId=#{rid}")
public List<Integer> selectAllPermissionId(int rid);
//删除关联表中当前账号信息
@Delete("delete from role_permission where roleId=#{rid}")
public int deletePermissionByRId(int rid);
//添加关联数据
public int addPermissionByList(@Param("rid") Integer rid, @Param("ids") List<Integer> ids);<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yunhe.mapper.RoleMapper">
<insert id="addPermissionByList" >
insert into role_permission (roleId,permissionId) values
<foreach collection="ids" item="pid" separator=",">
(#{rid},#{pid})
</foreach>
</insert>
</mapper>
编写RoleService
//根据角色id查询角色信息public Role findById(int id);
//修改角色信息
public int edit(Role role);
//查询指定角色响应的权限信息
public List<Integer> findPermissionByRid(int rid);
//为指定角色添加权限信息
public void permissionAdd(Integer rid,List<Integer> ids);@Override
public Role findById(int id) {
return roleMapper.selectById(id);
}
@Override
public int edit(Role role) {
return roleMapper.update(role);
}
@Override
public List<Integer> findPermissionByRid(int rid) {
return roleMapper.selectAllPermissionId(rid);
}
@Override
@Transactional
public void permissionAdd(Integer rid, List<Integer> ids) {
//先删除关联表中当前角色对应的所有权限
roleMapper.deletePermissionByRId(rid);
//使用集合在权限管理表中添加数据
roleMapper.addPermissionByList(rid,ids);
}
编写RoleController
@RequestMapping(value = "/edit",method = RequestMethod.GET)public String findById(HttpServletRequest request,int id){
Role role = roleService.findById(id);
request.setAttribute("role",role);
return "/role/role-edit";
}
@RequestMapping(value = "/edit",method = RequestMethod.POST)
public String edit(Role role){
roleService.edit(role);
return "redirect:/role/findAll";
}
@RequestMapping(value = "/permissionAdd",method = RequestMethod.GET)
public String toPermissionsAdd(HttpServletRequest request,int id){
//先查询当前角色拥有的权限
List<Integer> permissionIdList = roleService.findPermissionByRid(id);
//将当前角色拥有的权限发送
request.setAttribute("permissionIdList",permissionIdList);
//查询所有权限数据
List<Permission> permissionList = permissionService.findAll();
//将所有权限发送
request.setAttribute("permissionList",permissionList);
request.setAttribute("roleId",id);
return "/role/role-edit-permission";
}
@RequestMapping(value = "/permissionAdd",method = RequestMethod.POST)
@ResponseBody
public String toPermissionsAdd(@RequestBody Role_Pid ids){
roleService.permissionAdd(ids.getRid(),ids.getIds());
return "/role/findAll";
}
测试
2.4 角色详情
编写RoleMapper接口
//查询指定角色与权限信息public Role selectRole(int rid);<resultMap id="u_r" type="com.yunhe.javabean.Role" autoMapping="true">
<id column="id" property="id"></id>
<collection property="permissions" autoMapping="true" ofType="com.yunhe.javabean.Permission">
<id column="pid" property="id"></id>
</collection>
</resultMap>
<select id="selectRole" resultMap="u_r">
select r.*,p.id pid,p.permissionName,p.url from role r, role_permission rp, permission p where r.id=rp.roleId and p.id=rp.permissionId and r.id=#{id}
</select>
编写RoleService
//角色权限关联查询public Role findRole(int id);@Override
public Role findRole(int id) {
return roleMapper.selectRole(id);
}
编写RoleController
@RequestMapping(value = "/show")public String show(HttpServletRequest request,int id){
Role role = roleService.findRole(id);
request.setAttribute("role",role);
return "/role/role-show";
}
测试
2.5 角色删除
编写RoleMapper接口
//删除角色信息@Delete("delete from role where id=#{id}")
public int deleteById(int id);
编写RoleService
//删除角色信息public int deleteById(int id);@Override
public int deleteById(int id) {
return roleMapper.deleteById(id);
}
编写RoleController
@RequestMapping(value = "/delete")public String delete(int id){
roleService.deleteById(id);
return "redirect:/role/findAll";
}
测试
三、用户管理
3.1 查询用户
编写UserMapper接口
public interface UserMapper {//查询所有用户信息(包含权限)
public List<Users> selectAllUser();
}<resultMap id="u_r" type="com.yunhe.javabean.Users" autoMapping="true">
<association property="role" javaType="com.yunhe.javabean.Role" autoMapping="true">
<id column="roleId" property="id"/>
</association>
</resultMap>
<select id="selectAllUser" resultMap="u_r">
select u.*,ur.roleId,r.roleName,r.roleDesc from users u,users_role ur, role r where u.id=ur.userId and r.id=ur.roleId
</select>
编写UserService
public interface UserService extends UserDetailsService {/**
* 查询所有用户
* @return
*/
public List<Users> findAllUser();
}@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
/**
* 查询所有用户
* @return
*/
@Override
public List<Users> findAllUser() {
return userMapper.selectAllUser();
}
}
编写UserController
@Controller@RequestMapping("/users")
public class UserController {
@Autowired
UserService userService;
@Autowired
RoleService roleService;//之后查询角色信息使用
@RequestMapping("/findAll")
public String findAll(HttpServletRequest request, @RequestParam(value = "page",required = false,defaultValue = "1") int page, @RequestParam(value = "limit",required = false,defaultValue = "5")int limit){
PageHelper.startPage(page,limit);
List<Users> allUser = userService.findAllUser();
PageInfo<Users> pageInfo=new PageInfo<>(allUser);
request.setAttribute("pageInfo",pageInfo);
return "/users/users-list";
}
}
测试
3.2 用户添加
编写UserMapper接口
//添加用户数据public int insert(Users users);
//添加用户角色关联表数据
//将关联表中指定userid对应的roleid添加
@Insert("insert into users_role (userId,roleId)values(#{uid},#{rid})")
public int InsertUserRole(@Param("uid") int uid,@Param("rid") int rid);<insert id="insert" parameterType="com.yunhe.javabean.Users" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
insert users (username,password,email,phoneNum,status)values(#{username},#{password},#{email},#{phoneNum},#{status})
</insert>
编写UserService
public interface UserService extends UserDetailsService {/**
* 新增用户
* @param users rid
*/
public boolean add(Users users,int rid);
}@Override
@Transactional
public boolean add(Users users,int rid) {
//添加数据前将密码加密
users.setPassword(passwordEncoder.encode(users.getPassword()));
//向用户表中添加数据
userMapper.insert(users);
//向用户角色关联表中添加数据
userMapper.InsertUserRole(users.getId(),rid);
return true;
}
注意事项:
在添加用户时,我们还要将用户的密码,进行加密操作,在SpringSecurity中已经帮我们提供了实现,直接使用即可!
在【spring-securiyt.xml】中我们配置BCryptPasswordEncoder;加密类
<!-- 在xml配置加密类 --><bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
编写UserController
@RequestMapping(value = "/add",method = RequestMethod.GET)public String toAdd(HttpServletRequest request){
//查询角色列表数据
List<Role> roleList = roleService.findAll();
request.setAttribute("roleList",roleList);
return "/users/users-add";
}
@RequestMapping(value = "/add",method = RequestMethod.POST)
public String add(Users users,int roleId){
userService.add(users,roleId);
return "redirect:/users/findAll";
}
测试
3.3 用户删除
编写UserMapper接口
//添加用户数据public int insert(Users users);
//添加用户角色关联表数据
//将关联表中指定userid对应的roleid添加
@Insert("insert into users_role (userId,roleId)values(#{uid},#{rid})")
public int InsertUserRole(@Param("uid") int uid,@Param("rid") int rid);<insert id="insert" parameterType="com.yunhe.javabean.Users" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
insert users (username,password,email,phoneNum,status)values(#{username},#{password},#{email},#{phoneNum},#{status})
</insert>
编写UserService
public interface UserService extends UserDetailsService {/**
* 新增用户
* @param users rid
*/
public boolean add(Users users,int rid);
}@Override
@Transactional
public boolean add(Users users,int rid) {
//添加数据前将密码加密
users.setPassword(passwordEncoder.encode(users.getPassword()));
//向用户表中添加数据
userMapper.insert(users);
//向用户角色关联表中添加数据
userMapper.InsertUserRole(users.getId(),rid);
return true;
}
注意事项:
在添加用户时,我们还要将用户的密码,进行加密操作,在SpringSecurity中已经帮我们提供了实现,直接使用即可!
在【spring-securiyt.xml】中我们配置BCryptPasswordEncoder;加密类
<!-- 在xml配置加密类 --><bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
编写UserController
@RequestMapping(value = "/add",method = RequestMethod.GET)public String toAdd(HttpServletRequest request){
//查询角色列表数据
List<Role> roleList = roleService.findAll();
request.setAttribute("roleList",roleList);
return "/users/users-add";
}
@RequestMapping(value = "/add",method = RequestMethod.POST)
public String add(Users users,int roleId){
userService.add(users,roleId);
return "redirect:/users/findAll";
}
测试
3.4 问题处理
问题一:之前账号不能登录
用户的添加功能已经实现,当我们使用新添加的用户名进行登录时发现没办法登录的。
原因是,我们的密码是进行加密的,要登录时要对密码进行解密,在UserService中将查询到的UserInfo封装到了User对象中,此处我们有一段代码也是要修改,将{noop}给删掉
User user = new User(userInfo.getUsername(),// "{noop}"+userInfo.getPassword(),
userInfo.getPassword(),
userInfo.getStatus() == 0 ? false : true ,
true,true,true,
getAuthority(userInfo.getRoles()));
最后我们在spring-security.xml配置文件中也要进行配置
此时我们再进行测试,看是否能登录成功!!! 哈哈已经登录成功了
问题二:对jack密码进行加密
但是问题也就出现了,原来的jack用户名没办法登录了,原因是我们之间用的是明文进行登录的,密码没有进行加密,我们可以进行手动的进行加密把jack的密码给改一下即可!
编写BCryptPasswordEncoderUtil工具类
public class BCryptPasswordEncoderUtil {private static BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
public static String encoderPassword(String password){
String encoderPasswordStr = bCryptPasswordEncoder.encode(password);
return encoderPasswordStr;
}
public static void main(String[] args) {
String s = encoderPassword("123");
System.out.println(s);
}
}
问题三:登录页面账号名称显示
可以修改配置文件中认证成功后转发地址,设置为自定义的请求
然后再响应位置书写代码获取主体中认证成功的账号信息,存入session跳转成功页面即可
//....一级目录/users@RequestMapping("/name")
public String getUsername(HttpServletRequest request){
SecurityContext context = SecurityContextHolder.getContext();
UserDetails userDetails= (UserDetails)context.getAuthentication().getPrincipal();
request.getSession().setAttribute("username",userDetails.getUsername());
return "main";
}