黑马ssm学习笔记-企业权限管理系统

课程介绍

黑马ssm学习笔记-企业权限管理系统_第1张图片

SVN(功能类似GIT)

黑马ssm学习笔记-企业权限管理系统_第2张图片

AdminLTE前端模板

https://github.com/itheima2017/adminlte2-itheima

课程安排

黑马ssm学习笔记-企业权限管理系统_第3张图片

1. 在数据库中建表

黑马ssm学习笔记-企业权限管理系统_第4张图片
创建触发器,使用uuid();

use ssm;

drop table if exists product ;

create table product(
       id varchar(32) primary key,
       productNum varchar(50) not null,
       productName varchar(50),
       cityName varchar(50),
       DepartureTime timestamp,
       productPrice double,
       productDesc varchar(500),
       productStatus int,
       constraint product unique (id, productNum)
)engine innoDB default charset=utf8;

create trigger product_before_insert before insert on product for each row
begin
if new.id = '1' then
   set new.id = upper(replace(uuid(), '-', ''));
end if;
end;

insert into PRODUCT (id, productnum, productname, cityname, departuretime, productprice,
productdesc, productstatus)
values ('676C5BD1D35E429A8C2E114939C5685A', 'itcast-002', '北京三日游', '北京', '20181010101000', 1200, '不错的旅行', 1);
insert into PRODUCT (id, productnum, productname, cityname, departuretime, productprice,
productdesc, productstatus)
values ('12B7ABF2A4C544568B0A7C69F36BF8B7', 'itcast-003', '上海五日游', '上海', '20180425143000', 1800, '魔都我来了', 0);
insert into PRODUCT (id, productnum, productname, cityname, departuretime, productprice,
productdesc, productstatus)
values ('9F71F01CB448476DAFB309AA6DF9497F', 'itcast-001', '北京三日游', '北京', '20181010101000', 1200, '不错的旅行', 1);

insert into PRODUCT (productnum, productname, cityname, departuretime, productprice,
productdesc, productstatus)
values ('itcast-004', '北京三日游', '北京', '20181010101000', 1200, '不错的旅行', 1);

2. 创建父工程project:heima_ssm

跳过骨架
黑马ssm学习笔记-企业权限管理系统_第5张图片
黑马ssm学习笔记-企业权限管理系统_第6张图片

3. 创建子模块module:heima_ssm_dao

黑马ssm学习笔记-企业权限管理系统_第7张图片

4. 创建子模块module:heima_ssm_service

5. 创建子模块module:heima_ssm_utils

6. 使用骨架创建子模块module:heima_ssm_web

7. 在父工程中pom.xml导入jar包

黑马ssm学习笔记-企业权限管理系统_第8张图片

8. 编写实体类Product

黑马ssm学习笔记-企业权限管理系统_第9张图片

9. 创建接口IProductDao

黑马ssm学习笔记-企业权限管理系统_第10张图片
黑马ssm学习笔记-企业权限管理系统_第11张图片

10. 创建接口IProductService

黑马ssm学习笔记-企业权限管理系统_第12张图片

11. 创建实现类ProductServiceImpl

黑马ssm学习笔记-企业权限管理系统_第13张图片

12. 配置文件

黑马ssm学习笔记-企业权限管理系统_第14张图片

13. 在heima_ssm_web的resources下创建applicationContext.xml, spring-mvc.xml, db.properties

14. applicationContext.xml

1)导入头部约束

黑马ssm学习笔记-企业权限管理系统_第15张图片

2)开启注解扫描

黑马ssm学习笔记-企业权限管理系统_第16张图片

3)Spring整合mybatis

黑马ssm学习笔记-企业权限管理系统_第17张图片

4)配置事务

在这里插入图片描述

5)扫描dao接口

在这里插入图片描述

15. db.properties

在这里插入图片描述

16. spring-mvc.xml

1)导入头部约束

黑马ssm学习笔记-企业权限管理系统_第18张图片

2)扫描controller

在这里插入图片描述

3)配置视图解析器

在这里插入图片描述

4)设置静态资源不过滤

在这里插入图片描述

5)开启对springMVC的注解支持

在这里插入图片描述

6)AOP注解支持

黑马ssm学习笔记-企业权限管理系统_第19张图片

17. web.xml

1)导入头部约束

在这里插入图片描述

2)配置加载类路径的配置文件

在这里插入图片描述

3)配置监听器

在这里插入图片描述

4)前端控制器

黑马ssm学习笔记-企业权限管理系统_第20张图片

5)解决中文乱码的过滤器

黑马ssm学习笔记-企业权限管理系统_第21张图片

6)指定默认加载页面

黑马ssm学习笔记-企业权限管理系统_第22张图片

18. 创建ProductController

黑马ssm学习笔记-企业权限管理系统_第23张图片
黑马ssm学习笔记-企业权限管理系统_第24张图片

19. 流程

黑马ssm学习笔记-企业权限管理系统_第25张图片

20. 创建pages/product-list.jsp

黑马ssm学习笔记-企业权限管理系统_第26张图片

21. index.jsp

黑马ssm学习笔记-企业权限管理系统_第27张图片

22. 导入css, img, plugins

黑马ssm学习笔记-企业权限管理系统_第28张图片
黑马ssm学习笔记-企业权限管理系统_第29张图片

23. 复制aside.jsp, header.jsp

黑马ssm学习笔记-企业权限管理系统_第30张图片

24. 在heima_ssm_web的pom.xml

黑马ssm学习笔记-企业权限管理系统_第31张图片
黑马ssm学习笔记-企业权限管理系统_第32张图片

25. Product

黑马ssm学习笔记-企业权限管理系统_第33张图片
黑马ssm学习笔记-企业权限管理系统_第34张图片

26. 创建DateUtils

黑马ssm学习笔记-企业权限管理系统_第35张图片

27. clean

黑马ssm学习笔记-企业权限管理系统_第36张图片

28. install

黑马ssm学习笔记-企业权限管理系统_第37张图片

29. Webapp:clean

黑马ssm学习笔记-企业权限管理系统_第38张图片

30. 复制main.jsp

黑马ssm学习笔记-企业权限管理系统_第39张图片

31. index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<body>
    <jsp:forward page="pages/main.jsp"></jsp:forward>
</body>
</html>

添加产品

32. 导入product-add.jsp

33. ProductController

黑马ssm学习笔记-企业权限管理系统_第40张图片

34. IProductService

黑马ssm学习笔记-企业权限管理系统_第41张图片

35. ProductServiceImpl

黑马ssm学习笔记-企业权限管理系统_第42张图片

36. IProductDao

在这里插入图片描述

37. 添加产品

黑马ssm学习笔记-企业权限管理系统_第43张图片

38. 需要将页面上的日期转换

  1. 局部
    在这里插入图片描述

39. 创建orders

黑马ssm学习笔记-企业权限管理系统_第44张图片

40. 创建旅客信息traveller

黑马ssm学习笔记-企业权限管理系统_第45张图片

--创建旅客表
drop table if exists traveller;
CREATE TABLE traveller(
  id varchar(32) PRIMARY KEY,
  NAME VARCHAR(20),
  sex VARCHAR(20),
  phoneNum VARCHAR(20),
  credentialsType INT,
  credentialsNum VARCHAR(50),
  travellerType INT
);
create trigger traveller_before_insert before insert on traveller for each row
begin
if new.id = '1' then
   set new.id = upper(replace(uuid(), '-', ''));
end if;
end;
insert into TRAVELLER (id, name, sex, phonenum, credentialstype, credentialsnum, travellertype)
values ('3FE27DF2A4E44A6DBC5D0FE4651D3D3E', '张龙', '男', '13333333333', 0, '123456789009876543', 0);
insert into TRAVELLER (id, name, sex, phonenum, credentialstype, credentialsnum, travellertype)
values ('EE7A71FB6945483FBF91543DBE851960', '张小龙', '男', '15555555555', 0, '987654321123456789', 1);

41. 创建旅客和订单的中间表order_traveller

黑马ssm学习笔记-企业权限管理系统_第46张图片

-- 订单与旅客中间表
drop table if exists order_traveller;
CREATE TABLE order_traveller(
  orderId varchar(32),
  travellerId varchar(32),
  PRIMARY KEY (orderId,travellerId),
  FOREIGN KEY (orderId) REFERENCES orders(id),
  FOREIGN KEY (travellerId) REFERENCES traveller(id)
);

insert into ORDER_TRAVELLER (orderid, travellerid)
values ('0E7231DC797C486290E8713CA3C6ECCC', '3FE27DF2A4E44A6DBC5D0FE4651D3D3E');
insert into ORDER_TRAVELLER (orderid, travellerid)
values ('2FF351C4AC744E2092DCF08CFD314420', '3FE27DF2A4E44A6DBC5D0FE4651D3D3E');
insert into ORDER_TRAVELLER (orderid, travellerid)
values ('3081770BC3984EF092D9E99760FDABDE', 'EE7A71FB6945483FBF91543DBE851960');
insert into ORDER_TRAVELLER (orderid, travellerid)
values ('55F9AF582D5A4DB28FB4EC3199385762', 'EE7A71FB6945483FBF91543DBE851960');
insert into ORDER_TRAVELLER (orderid, travellerid)
values ('5DC6A48DD4E94592AE904930EA866AFA', '3FE27DF2A4E44A6DBC5D0FE4651D3D3E');
insert into ORDER_TRAVELLER (orderid, travellerid)
values ('96CC8BD43C734CC2ACBFF09501B4DD5D', 'EE7A71FB6945483FBF91543DBE851960');
insert into ORDER_TRAVELLER (orderid, travellerid)
values ('A0657832D93E4B10AE88A2D4B70B1A28', '3FE27DF2A4E44A6DBC5D0FE4651D3D3E');
insert into ORDER_TRAVELLER (orderid, travellerid)
values ('CA005CF1BE3C4EF68F88ABC7DF30E976', 'EE7A71FB6945483FBF91543DBE851960');
insert into ORDER_TRAVELLER (orderid, travellerid)
values ('E4DD4C45EED84870ABA83574A801083E', 'EE7A71FB6945483FBF91543DBE851960');

所有订单查询

黑马ssm学习笔记-企业权限管理系统_第47张图片

42. 创建订单实体类domain.Orders

黑马ssm学习笔记-企业权限管理系统_第48张图片

43. 创建会员实体类domain.Member

44. 创建旅客实体类domain.Traveller

45. 创建控制器OrderController

黑马ssm学习笔记-企业权限管理系统_第49张图片

46. 创建service接口IOrdersService

47. 创建service实现类impl.OrederServiceImpl

黑马ssm学习笔记-企业权限管理系统_第50张图片

48. 创建dao接口dao.IOrdersDao

黑马ssm学习笔记-企业权限管理系统_第51张图片

49. 在ProductDao中创建findById()

pagehelper的使用

50. 导入maven依赖

黑马ssm学习笔记-企业权限管理系统_第52张图片

51. 配置

1. 如果没有使用Spring在Mybatis中xml配置:

黑马ssm学习笔记-企业权限管理系统_第53张图片

2. 在Spring中配置

黑马ssm学习笔记-企业权限管理系统_第54张图片
黑马ssm学习笔记-企业权限管理系统_第55张图片

52. 在service中配置

黑马ssm学习笔记-企业权限管理系统_第56张图片

53. 在aside.jsp中传入参数

在这里插入图片描述

54. OrdersController

黑马ssm学习笔记-企业权限管理系统_第57张图片

55. IOrderService

黑马ssm学习笔记-企业权限管理系统_第58张图片

56. OrderServiceImpl

黑马ssm学习笔记-企业权限管理系统_第59张图片

57. orders-page-list.jsp中取pageInfo.list

黑马ssm学习笔记-企业权限管理系统_第60张图片

58. orders-page-list.jsp中页码跳转

黑马ssm学习笔记-企业权限管理系统_第61张图片

59. orders-page-list.jsp中改变每页显示的条数

黑马ssm学习笔记-企业权限管理系统_第62张图片

黑马ssm学习笔记-企业权限管理系统_第63张图片

订单详情

黑马ssm学习笔记-企业权限管理系统_第64张图片

1. orders-page-list.jsp发出请求

在这里插入图片描述

2. OrdersController

黑马ssm学习笔记-企业权限管理系统_第65张图片

3. IOrdersService

黑马ssm学习笔记-企业权限管理系统_第66张图片

4. OrdersServiceImpl

黑马ssm学习笔记-企业权限管理系统_第67张图片

5. IOrdersDao

黑马ssm学习笔记-企业权限管理系统_第68张图片
在这里插入图片描述

6. IMemberDao

黑马ssm学习笔记-企业权限管理系统_第69张图片

7. ITravellerDao

在这里插入图片描述

用户权限管理

黑马ssm学习笔记-企业权限管理系统_第70张图片

1. 建立users表

drop table if exists users;
create table users(
       id varchar(32) default '1' primary key,
       email varchar(50) unique not null,
       username varchar(50),
       password varchar(50),
       phoneNum varchar(20),
       status int
)engine innodb default charset=utf8;

create trigger users_before_insert before insert on users for each row
begin
if new.id = '1' then
   set new.id = upper(replace(uuid(), '-', ''));
end if;
end;

2. 建立role表

-- 建立role
drop table if exists role;
create table role(
       id varchar(32) default '1' primary key,
       roleName varchar(50),
       roleDesc varchar(50)
)engine innodb default charset=utf8;

create trigger role_before_insert before insert on role for each row
begin
if new.id = '1' then
   set new.id = upper(replace(uuid(), '-', ''));
end if;
end;

3. 建立users_role表

-- 建立users_role
drop table if exists users_role;
create table users_role(
       userId varchar(32),
       roleId varchar(32),
       primary key (userId, roleId),
       foreign key (userId) references users(id),
       foreign key (roleId) references role(id)
)engine innodb default charset=utf8;

4. 建立peimission表

-- 建立peimission表
create table permission(
       id varchar(32) default '1' primary key,
       permissionName varchar(50),
       url varchar(50)     
)engine innodb default charset=utf8;

5. 建立role_permission表

-- 建立role_permission表
create table role_permission(
       permissionId varchar(32),
       roleId varchar(32),
       primary key (permissionId, roleId),
       foreign key (permissionId) references permission(id),
       foreign key (roleId) references role(id)
)engine innodb default charset=utf8;

6. 在web.xml中配置springSecurity过滤器

黑马ssm学习笔记-企业权限管理系统_第71张图片

7. 创建spring-security.xml文件


<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:security="http://www.springframework.org/schema/security"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans          
    http://www.springframework.org/schema/beans/spring-beans.xsd          
    http://www.springframework.org/schema/security          
    http://www.springframework.org/schema/security/spring-security.xsd">
    
    
    <security:http pattern="/login.jsp" security="none"/>
    <security:http pattern="/failer.jsp" security="none"/>
    <security:http pattern="/css/**" security="none"/>
    <security:http pattern="/img/**" security="none"/>
    <security:http pattern="/plugins/**" security="none"/>
    
    
    <security:http auto-config="true" use-expressions="false">
    	
    	<security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/>
    	
    	
    	<security:form-login  
    		login-page="/login.jsp"
    		login-processing-url="/login.jsp"
    		default-target-url="/index.jsp"
    		authentication-failure-url="/failer.jsp"
		authentication-success-forward-url="/pages/main.jsp"
    	/>
    	
    	
    	<security:csrf disabled="true"/>
    	
    	
    	<security:logout invalidate-session="true" logout-url="/logout.do" logout-success-url="/login.jsp" />
    	
    security:http>
    
    
    <security:authentication-manager>
    	<security:authentication-provider user-service-ref="userService">
    		
    		<security:password-encoder ref="passwordEncoder"/>
    	security:authentication-provider>
    security:authentication-manager>
    
    
    <bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
    
    
    
 beans>   

8. 在web.xml中导入


  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath*:applicationContext.xml,classpath*:spring-security.xmlparam-value>
  context-param>
  
  <filter>
    <filter-name>springSecurityFilterChainfilter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
  filter>
  <filter-mapping>
    <filter-name>springSecurityFilterChainfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>

9. 创建IUserService继承UserDetailsService

public interface IUserService extends UserDetailsService {
     
}

10. 创建UserServiceImpl重写loadUserByUsername()

@Service("userService")
public class UserServiceImpl implements IUserService {
     

    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
     
        return null;
    }
}

11. 创建IUserDao

@Repository
public interface IUserDao {
     
    
    @Select("select * from users where username = #{username}")
    UserInfo findByUsername(String username);
}

12. 创建UserInfo

    private String id;
    private String username;
    private String email;
    private String password;
    private String phoneNum;
    private int status;
    private String statusStr;
    private List<Role> roles;

13. 创建Role

    private String id;
    private String roleName;
    private String roleDesc;
    private List<Permission> permissions;
    private List<UserInfo> users;

14. 创建Permission

    private String id;
    private String permissionName;
    private String url;
    private List<Role> roles;

15. 完善UserServiceImpl

@Service("userService")
public class UserServiceImpl implements IUserService {
     

    @Autowired
    private IUserDao userDao;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
     
        UserInfo userInfo = userDao.findByUsername(username);

        // 处理自己的用户对象封装成UserDetails
        User user = new User(userInfo.getUsername(), userInfo.getPassword(), null);
        return user;
    }
}

16. 效果(没有设置权限)

黑马ssm学习笔记-企业权限管理系统_第72张图片
黑马ssm学习笔记-企业权限管理系统_第73张图片

17. 在UsersServiceImpl中模拟设置权限

@Service("userService")
@Transactional
public class UserServiceImpl implements IUserService {
     

    @Autowired
    private IUserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
     
        UserInfo userInfo = userDao.findByUsername(username);

        // 处理自己的用户对象封装成UserDetails
        User user = new User(userInfo.getUsername(), "{noop}"+userInfo.getPassword(), getAuthority());
        return user;
    }

    public List<SimpleGrantedAuthority> getAuthority(){
     
        List<SimpleGrantedAuthority> list = new ArrayList<SimpleGrantedAuthority>();
        list.add(new SimpleGrantedAuthority("ROLE_USER"));
        return list;
    }
}

18. 执行效果

若登录失败

黑马ssm学习笔记-企业权限管理系统_第74张图片

  1. userInfo.getPassword()加上"{noop}"
 User user = new User(userInfo.getUsername(), "{noop}"+userInfo.getPassword(), getAuthority());
  1. spring-security中
    
    <security:authentication-manager>
        <security:authentication-provider user-service-ref="userService">
            
        security:authentication-provider>
    security:authentication-manager>

登录成功

黑马ssm学习笔记-企业权限管理系统_第75张图片

从数据库中获取角色

19. 修改UsersServiceImpl

@Service("userService")
@Transactional
public class UserServiceImpl implements IUserService {
     

    @Autowired
    private IUserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
     
        UserInfo userInfo = userDao.findByUsername(username);
        List<Role> roles = userInfo.getRoles();

        List<SimpleGrantedAuthority> authorities = getAuthority(roles);

        // 处理自己的用户对象封装成UserDetails
        User user = new User(userInfo.getUsername(), "{noop}"+userInfo.getPassword(),
                userInfo.getStatus() == 0?false:true, true, true, true, authorities);
        return user;
    }

    public List<SimpleGrantedAuthority> getAuthority(List<Role> roles){
     
        List<SimpleGrantedAuthority> list = new ArrayList<SimpleGrantedAuthority>();
        for (Role role : roles) {
     
            list.add(new SimpleGrantedAuthority(role.getRoleName()));
        }
        return list;
    }
}

20. 修改IUserDao

@Repository
public interface IUserDao {
     

    @Select("select * from users where username = #{username}")
    @Results({
     
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "username", column = "username"),
            @Result(property = "email", column = "email"),
            @Result(property = "password", column = "password"),
            @Result(property = "phoneNum", column = "phoneNum"),
            @Result(property = "status", column = "status"),
            @Result(property = "roles", column = "id", javaType = List.class,
                    many = @Many(select = "com.itheima.ssm.dao.IRoleDao.findRoleByUserId"))

    })
    UserInfo findByUsername(String username);
}

21. 创建IRoleDao

@Repository
public interface IRoleDao {
     

    @Select("select * from role where id in (select roleId from users_role where userId = #{userId})")
    List<Role> findRoleByUserId(String userId);
}

22. 登录成功

注销

1. header.jsp

							<div class="pull-right">
								<a href="${pageContext.request.contextPath}/logout.do"
									class="btn btn-default btn-flat">注销</a>
							</div>

2. spring-security.xml

        
        <security:logout invalidate-session="true" logout-url="/logout.do" logout-success-url="/login.jsp" />

用户查询

黑马ssm学习笔记-企业权限管理系统_第76张图片
黑马ssm学习笔记-企业权限管理系统_第77张图片

1. 创建UserController

@Controller
@RequestMapping("/user")
public class UserController {
     

    @Autowired
    private IUserService userService = new UserServiceImpl();

    @RequestMapping("/findAll.do")
    public ModelAndView findAll(){
     
        ModelAndView mv = new ModelAndView();
        List<UserInfo> userInfos = userService.findAll();
        mv.addObject("userList", userInfos);
        mv.setViewName("user-list");

        return mv;
    }
}

2. 在IUserService中创建函数

public interface IUserService extends UserDetailsService {
     
    List<UserInfo> findAll();
}

3. 在UserServiceImpl中实现函数

    @Override
    public List<UserInfo> findAll() {
     
        List<UserInfo> userInfos= userDao.findAll();
        return userInfos;
    }

4. 在IUserDao中实现查询

    @Select("select * from users")
    List<UserInfo> findAll();

5. 效果

黑马ssm学习笔记-企业权限管理系统_第78张图片

用户添加

1. user-add.jsp

在这里插入图片描述

2. UserController

    @RequestMapping("/save.do")
    public String save(UserInfo userInfo){
     
        userService.save(userInfo);
        return "redirect:findAll.do";
    }

3. IUserService

    void save(UserInfo userInfo);

4. UserServiceImpl

    @Override
    public void save(UserInfo userInfo) {
     
        userDao.save(userInfo);
    }

5. IUserDao

    @Insert("insert into users(email, username, password, phoneNum, status) values (#{email}, #{username}, #{password}, #{phoneNum}, #{status})")
    void save(UserInfo userInfo);

要实现密码加密

6. spring-security

    <!-- 配置加密类 -->
    <bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>

7. 修改UserServiceImpl

    @Override
    public void save(UserInfo userInfo) {
     

        // 密码加密
        userInfo.setPassword(bCryptPasswordEncoder.encode(userInfo.getPassword()));
        userDao.save(userInfo);
    }

8. 效果

9. spring-security.xml配置加密方式

    
    <security:authentication-manager>
        <security:authentication-provider user-service-ref="userService">
            
            <security:password-encoder ref="passwordEncoder"/>
        security:authentication-provider>
    security:authentication-manager>

10. UserController中去掉{noop}

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
     
        UserInfo userInfo = userDao.findByUsername(username);
        List<Role> roles = userInfo.getRoles();

        List<SimpleGrantedAuthority> authorities = getAuthority(roles);

        // 处理自己的用户对象封装成UserDetails
        User user = new User(userInfo.getUsername(), "{noop}"+userInfo.getPassword(),
                userInfo.getStatus() == 0?false:true, true, true, true, authorities);
        return user;
    }

用户详情查询

黑马ssm学习笔记-企业权限管理系统_第79张图片

1. user-list.jsp

<a href="${pageContext.request.contextPath}/user/findById.do?id=${user.id}" class="btn bg-olive btn-xs">详情</a>

2. UserController

    @RequestMapping("/findById.do")
    public ModelAndView findById(@RequestParam(name = "id", required = true)String id) {
     
        ModelAndView mv = new ModelAndView();
        UserInfo userInfo = userService.findById(id);

        mv.addObject("user", userInfo);
        mv.setViewName("user-show");
        return mv;
    }

3. IUserService

public interface IUserService extends UserDetailsService {
     

    List<UserInfo> findAll();

    void save(UserInfo userInfo);

    UserInfo findById(String id);
}

4. UserServiceImpl

    @Override
    public UserInfo findById(String id) {
     
        return userDao.findById(id);
    }

5. IUserDao

    @Select("select * from users where id = #{id}")
    @Results({
     
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "username", column = "username"),
            @Result(property = "email", column = "email"),
            @Result(property = "password", column = "password"),
            @Result(property = "phoneNum", column = "phoneNum"),
            @Result(property = "status", column = "status"),
            @Result(property = "roles", column = "id", javaType = List.class,
                    many = @Many(select = "com.itheima.ssm.dao.IRoleDao.findRoleByUserId"))

    })
    UserInfo findById(String id);

6. IRoleDao

@Repository
public interface IRoleDao {
     

    @Select("select * from role where id in (select roleId from users_role where userId = #{userId})")
    @Results({
     
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "roleName", column = "roleName"),
            @Result(property = "roleDesc", column = "roleDesc"),
            @Result(property = "permissions", column = "id", javaType = List.class,
                    many = @Many(select = "com.itheima.ssm.dao.IPermissionDao.findByRoleId"))
    })
    List<Role> findRoleByUserId(String userId);
}

7. IPermissionDao

public interface IPermissionDao {
     

    @Select("select * from permission where id in (select permissionId from role_permission where roleId = #{roleId})")
    List<Permission> findByRoleId(String roleId);

}

角色查询

黑马ssm学习笔记-企业权限管理系统_第80张图片

1. RoleController

@Controller
@RequestMapping("/role")
public class RoleController {
     

    @Autowired
    private IRoleService roleService;

    @RequestMapping("/findAll.do")
    public ModelAndView findAll() {
     
        ModelAndView mv = new ModelAndView();
        List<Role> roles = roleService.findAll();

        mv.addObject("roleList", roles);
        mv.setViewName("role-list");

        return mv;

    }
}

2. IRoleService

@Service
public interface IRoleService {
     

    List<Role> findAll();
}

3. RoleServiceImpl

public class RoleServiceImpl implements IRoleService {
     
    
    @Autowired
    private IRoleDao roleDao;
    
    @Override
    public List<Role> findAll() {
     
        return roleDao.findAll();
    }
}

4. IRoleDao

    @Select("select * from role")
    List<Role> findAll();

角色添加

1. RoleController

    @RequestMapping("/save.do")
    public String save(Role role) {
     
        roleService.save(role);
        
        return "redirect:findAll.do";
    }

2. IRoleService

public interface IRoleService {
     

    List<Role> findAll();

    void save(Role role);
}

3. RoleServiceImpl

    @Override
    public void save(Role role) {
     
        roleDao.save(role);
    }

4. IRoleDao

    @Insert("insert into role(roleName, roleDesc) values(#{roleName}, #{roleDesc})")
    void save(Role role);

资源权限查询

1. aside.jsp

						href="${pageContext.request.contextPath}/permission/findAll.do">
							<i class="fa fa-circle-o"></i> 资源权限管理

2. PermissionController

@Controller
@RequestMapping("/permission")
public class PermissionController {
     

    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/findAll")
    public ModelAndView findAll(){
     
        ModelAndView mv = new ModelAndView();
        List<Permission> permissions = permissionService.findAll();
        mv.addObject("permissionList", permissions);
        mv.setViewName("permission-list");

        return mv;
    }
}

3. IPermissionService

public interface IPermissionService {
     

    List<Permission> findAll();
}

4. PermissionServiceImpl

    @Override
    public List<Permission> findAll() {
     
        return permissionDao.findAll();
    }

5. IPermissionDao

    @Select("select * from permission")
    List<Permission> findAll();

资源权限添加

1. PermissionController

    @RequestMapping("/save.do")
    public String save(Permission permission){
     
        permissionService.save(permission);
        return "redirect:findAll.do";
    }

2. IPermissionService

    void save(Permission permission);

3. PermissionServiceImpl

    @Override
    public void save(Permission permission) {
     
        permissionDao.save(permission);
    }

4. IPermissionDao

    @Insert("insert into permission (permissionName, url) values (#{permissionName}, #{url})")
    void save(Permission permission);

角色详情查询

角色删除

权限管理

黑马ssm学习笔记-企业权限管理系统_第81张图片

给用户添加角色

黑马ssm学习笔记-企业权限管理系统_第82张图片

1. user-list.jsp

<a href="${pageContext.request.contextPath}/user/findUserByIdAndAllRole.do?id=${user.id}" class="btn bg-olive btn-xs">添加角色a>

2. UserController

    @RequestMapping("/findUserByIdAndAllRole.do")
    public ModelAndView findUserByIdAndAllRole(@RequestParam(name = "id", required = true) String userid) {
     
        ModelAndView mv = new ModelAndView();
        UserInfo user = userService.findById(userid);
        mv.addObject("user", user);

        List<Role> otherRoles = userService.findOtherRoles(userid);
        mv.addObject("roleList", otherRoles);

        mv.setViewName("user-role-add");
        return mv;
    }

3. IUserService

    List<Role> findOtherRoles(String userid);

4. UserServiceImpl

    @Override
    public List<Role> findOtherRoles(String userid) {
     
        return userDao.findOtherRoles(userid);
    }

5. IUserDao

    @Select("select * from role where id not in (select roleId from users_role where userId = #{userid})")
    List<Role> findOtherRoles(String userid);

6. UserController

    @RequestMapping("/addRoleToUser.do")
    public String addRoleToUser(@RequestParam(name = "userId") String userId, @RequestParam(name = "ids") String[] roleIds){
     
        userService.addRoleToUser(userId, roleIds);
        return "redirect:findAll.do";
    }

7. IUserService

    void addRoleToUser(String userId, String[] roleIds);

8. UserServiceImpl

    @Override
    public void addRoleToUser(String userId, String[] roleIds) {
     
        for (String roleId : roleIds) {
     

            userDao.addRoleToUser(userId, roleId);
        }
    }

9. IUserDao

    @Insert("insert into users_role values (#{userId}, #{roleId})")
    void addRoleToUser(@Param("userId") String userId, @Param("roleId") String roleId);

给角色添加资源权限

1. UserController

    @RequestMapping("/findRoleByIdAndAllPermission.do")
    public ModelAndView findRoleByIdAndAllPermission(@RequestParam(name = "id") String roleId){
     
        ModelAndView mv = new ModelAndView();
        Role role = roleService.findById(roleId);
        mv.addObject("role", role);

        List<Permission> permissionList = roleService.findOtherPermissions(roleId);
        mv.addObject("permissionList", permissionList);

        mv.setViewName("role-permission-add");
        return mv;
    }

2. IRoleService

    List<Permission> findOtherPermissions(String roleId);

3. RoleServiceImpl

    @Override
    public List<Permission> findOtherPermissions(String roleId) {
     
        return roleDao.findOtherPermissions(roleId);
    }

4. IRoleDao

    @Select("select * from permission where id not in (select permissionId from role_permission where roleId = #{roleId})")
    List<Permission> findOtherPermissions(String roleId);

5. RoleController

    @RequestMapping("/addPermissionToRole.do")
    public String addPermissionToRole(@RequestParam("roleId") String roleId, @RequestParam("ids") String[] ids){
     
        roleService.addPermissionToRole(roleId, ids);
        return "redirect:findAll.do";
    }

6. IRoleService

    void addPermissionToRole(String roleId, String[] ids);

7. RoleServiceImpl

    @Override
    public void addPermissionToRole(String roleId, String[] ids) {
     
        for (String id : ids) {
     
            roleDao.addPermissionToRole(roleId, id);
        }
    }

8. IRoleDao

    @Insert("insert into role_permission values (#{id}, #{roleId})")
    void addPermissionToRole(@Param("roleId") String roleId, @Param("id") String id);

权限控制

1. jsr250

1) spring-security.xml中开启

<security:global-method-security jsr250-annotations="enabled"/>

2) 在指定的方法上使用,OrderController

    @RequestMapping("/findAll.do")
    @RolesAllowed("ADMIN")   // ROlE_可省
    public ModelAndView findAll(@RequestParam( name = "page", required = true, defaultValue = "1")Integer page,
                                @RequestParam( name = "size", required = true, defaultValue = "4")Integer size) {
     
        ModelAndView mv = new ModelAndView();
        List<Orders> orders = ordersService.findAll(page, size);
        PageInfo pageInfo = new PageInfo(orders);
        mv.addObject("pageInfo", pageInfo);
        mv.setViewName("orders-page-list");
        return mv;
    }

3) 在父工程的pom.xml中导入依赖

        <dependency>
            <groupId>javax.annotationgroupId>
            <artifactId>jsr250-apiartifactId>
            <version>1.0version>
        dependency>

4) 在web.xml中配置error page

  <error-page>
    <error-code>403error-code>
    <location>/403.jsplocation>
  error-page>

2. secured

1) spring-security.xml中开启

    <security:global-method-security secured-annotations="enabled"/>

2) 在指定的方法上使用,OrderController

    @RequestMapping("/findAll.do")
//    @RolesAllowed("ADMIN")   // ROlE_可省
    @Secured("ROLE_ADMIN")     // ROLE_不可省
    public ModelAndView findAll(@RequestParam( name = "page", required = true, defaultValue = "1")Integer page,
                                @RequestParam( name = "size", required = true, defaultValue = "4")Integer size) {
     
        ModelAndView mv = new ModelAndView();
        List<Orders> orders = ordersService.findAll(page, size);
        PageInfo pageInfo = new PageInfo(orders);
        mv.addObject("pageInfo", pageInfo);
        mv.setViewName("orders-page-list");
        return mv;
    }

3. 表达式

1) spring-security.xml中开启

    <security:global-method-security pre-post-annotations="enabled"/>

2) 在指定的方法上使用,OrderController

    @RequestMapping("/findAll.do")
//    @RolesAllowed("ADMIN")   // ROlE_可省
//    @Secured("ROLE_ADMIN")     // ROLE_不可省
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ModelAndView findAll(@RequestParam( name = "page", required = true, defaultValue = "1")Integer page,
                                @RequestParam( name = "size", required = true, defaultValue = "4")Integer size) {
     
        ModelAndView mv = new ModelAndView();
        List<Orders> orders = ordersService.findAll(page, size);
        PageInfo pageInfo = new PageInfo(orders);
        mv.addObject("pageInfo", pageInfo);
        mv.setViewName("orders-page-list");
        return mv;
    }

    @RequestMapping("/findById.do")
    @PreAuthorize("authentication.principal.username == 'sss'")
    public ModelAndView findById(@RequestParam(name = "id", required = true) String id) {
     
        ModelAndView mv = new ModelAndView();
        Orders orders = ordersService.findById(id);
        mv.addObject("orders", orders);
        mv.setViewName("orders-show");

        return mv;
    }

4. 页面端

黑马ssm学习笔记-企业权限管理系统_第83张图片

1) 导入依赖

        <dependency>
            <groupId>org.springframework.securitygroupId>
            <artifactId>spring-security-taglibsartifactId>
            <version>${spring.security.version}version>
        dependency>

2) 在页面导入

<%@taglib prefix="security" uri="http://www.springframework.org/security/tags" %>

在这里插入图片描述

3) 获取用户名

<security:authentication property="principal.username"/>

4) 管理标签是否可以看见

1. aside.jsp

					<li id="system-setting">
						<security:authorize access="hasRole('ROLE_ADMIN')">
						<a
						href="${pageContext.request.contextPath}/user/findAll.do"> <i
							class="fa fa-circle-o">i> 用户管理
					a>
						security:authorize>
					li>

2. spring-scurity.xml

  1. 改为表达式形式
    <security:http auto-config="true" use-expressions="true">
        
        <security:intercept-url pattern="/**" access="has('ROLE_USER','ROLE_ADMIN')"/>
  1. 不改为表达式形式,则要添加一个bean
    <bean id="webSecurityExpressionHandler" class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler"/>

AOP日志

1. 建表sysLog

-- 建立sysLog表
create table sysLog(
       id varchar(32) default '1' primary key,
       visitTime timestamp,
       username varchar(50),
       ip varchar(30),
       url varchar(50),
       executionTime int,
       method varchar(200)
)engine innodb default charset=utf8;

create trigger sysLog_before_insert before insert on sysLog for each row
begin
if new.id = '1' then
   set new.id = upper(replace(uuid(), '-', ''));
end if;
end;

2. 创建实体类SysLog

public class SysLog implements Serializable {
     

    private String id;
    private Date visitTime;
    private String visitTimeStr;
    private String username;
    private String ip;
    private String url;
    private Long executionTime;
    private String method;

3. 在controller下创建LogAOP

public class LogAOP {
     


    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ISysLogService sysLogService;

    private Date visitTime; //开始时间
    private Class clazz; //访问的类
    private Method method;//访问的方法

    //前置通知  主要是获取开始时间,执行的类是哪一个,执行的是哪一个方法
    @Before("execution(* com.itheima.ssm.controller.*.*(..))")
    public void doBefore(JoinPoint jp) throws NoSuchMethodException {
     
        visitTime = new Date();//当前时间就是开始访问的时间
        clazz = jp.getTarget().getClass(); //具体要访问的类
        String methodName = jp.getSignature().getName(); //获取访问的方法的名称
        Object[] args = jp.getArgs();//获取访问的方法的参数

        //获取具体执行的方法的Method对象
        if (args == null || args.length == 0) {
     
            method = clazz.getMethod(methodName); //只能获取无参数的方法
        } else {
     
            Class[] classArgs = new Class[args.length];
            for (int i = 0; i < args.length; i++) {
     
                classArgs[i] = args[i].getClass();
            }
            clazz.getMethod(methodName, classArgs);
        }
    }

    //后置通知
    @After("execution(* com.itheima.ssm.controller.*.*(..))")
    public void doAfter(JoinPoint jp) throws Exception {
     
        long time = new Date().getTime() - visitTime.getTime(); //获取访问的时长

        String url = "";
        //获取url
        if (clazz != null && method != null && clazz != LogAOP.class) {
     
            //1.获取类上的@RequestMapping("/orders")
            RequestMapping classAnnotation = (RequestMapping) clazz.getAnnotation(RequestMapping.class);
            if (classAnnotation != null) {
     
                String[] classValue = classAnnotation.value();
                //2.获取方法上的@RequestMapping(xxx)
                RequestMapping methodAnnotation = method.getAnnotation(RequestMapping.class);
                if (methodAnnotation != null) {
     
                    String[] methodValue = methodAnnotation.value();
                    url = classValue[0] + methodValue[0];

                    //获取访问的ip
                    String ip = request.getRemoteAddr();

                    //获取当前操作的用户
                    SecurityContext context = SecurityContextHolder.getContext();//从上下文中获了当前登录的用户
                    User user = (User) context.getAuthentication().getPrincipal();
                    String username = user.getUsername();

                    //将日志相关信息封装到SysLog对象
                    SysLog sysLog = new SysLog();
                    sysLog.setExecutionTime(time); //执行时长
                    sysLog.setIp(ip);
                    sysLog.setMethod("[类名] " + clazz.getName() + "[方法名] " + method.getName());
                    sysLog.setUrl(url);
                    sysLog.setUsername(username);
                    sysLog.setVisitTime(visitTime);

                    //调用Service完成操作
                    sysLogService.save(sysLog);
                }
            }
        }

    }
}

4. web.xml中配置request

  <listener>
    <listener-class>org.springframework.web.context.request.RequestContextListenerlistener-class>
  listener>

查询日志

你可能感兴趣的:(SSM)