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

  • Post author:
  • Post category:其他




课程介绍

在这里插入图片描述



SVN(功能类似GIT)

在这里插入图片描述



AdminLTE前端模板


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



课程安排

在这里插入图片描述



1. 在数据库中建表

在这里插入图片描述

创建触发器,使用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

跳过骨架

在这里插入图片描述

在这里插入图片描述



3. 创建子模块module:heima_ssm_dao

在这里插入图片描述



4. 创建子模块module:heima_ssm_service



5. 创建子模块module:heima_ssm_utils



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



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

在这里插入图片描述



8. 编写实体类Product

在这里插入图片描述



9. 创建接口IProductDao

在这里插入图片描述

在这里插入图片描述



10. 创建接口IProductService

在这里插入图片描述



11. 创建实现类ProductServiceImpl

在这里插入图片描述



12. 配置文件

在这里插入图片描述



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



14. applicationContext.xml



1)导入头部约束

在这里插入图片描述



2)开启注解扫描

在这里插入图片描述



3)Spring整合mybatis

在这里插入图片描述



4)配置事务

在这里插入图片描述



5)扫描dao接口

在这里插入图片描述



15. db.properties

在这里插入图片描述



16. spring-mvc.xml



1)导入头部约束

在这里插入图片描述



2)扫描controller

在这里插入图片描述



3)配置视图解析器

在这里插入图片描述



4)设置静态资源不过滤

在这里插入图片描述



5)开启对springMVC的注解支持

在这里插入图片描述



6)AOP注解支持

在这里插入图片描述



17. web.xml



1)导入头部约束

在这里插入图片描述



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

在这里插入图片描述



3)配置监听器

在这里插入图片描述



4)前端控制器

在这里插入图片描述



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

在这里插入图片描述



6)指定默认加载页面

在这里插入图片描述



18. 创建ProductController

在这里插入图片描述

在这里插入图片描述



19. 流程

在这里插入图片描述



20. 创建pages/product-list.jsp

在这里插入图片描述



21. index.jsp

在这里插入图片描述



22. 导入css, img, plugins

在这里插入图片描述

在这里插入图片描述



23. 复制aside.jsp, header.jsp

在这里插入图片描述



24. 在heima_ssm_web的pom.xml

在这里插入图片描述

在这里插入图片描述



25. Product

在这里插入图片描述

在这里插入图片描述



26. 创建DateUtils

在这里插入图片描述



27. clean

在这里插入图片描述



28. install

在这里插入图片描述



29. Webapp:clean

在这里插入图片描述



30. 复制main.jsp

在这里插入图片描述



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

在这里插入图片描述



34. IProductService

在这里插入图片描述



35. ProductServiceImpl

在这里插入图片描述



36. IProductDao

在这里插入图片描述



37. 添加产品

在这里插入图片描述



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

  1. 局部

    在这里插入图片描述



39. 创建orders

在这里插入图片描述



40. 创建旅客信息traveller

在这里插入图片描述

--创建旅客表
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

在这里插入图片描述

-- 订单与旅客中间表
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');



所有订单查询

在这里插入图片描述



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

在这里插入图片描述



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



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



45. 创建控制器OrderController

在这里插入图片描述



46. 创建service接口IOrdersService



47. 创建service实现类impl.OrederServiceImpl

在这里插入图片描述



48. 创建dao接口dao.IOrdersDao

在这里插入图片描述



49. 在ProductDao中创建findById()



pagehelper的使用



50. 导入maven依赖

在这里插入图片描述



51. 配置



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

在这里插入图片描述



2. 在Spring中配置

在这里插入图片描述

在这里插入图片描述



52. 在service中配置

在这里插入图片描述



53. 在aside.jsp中传入参数

在这里插入图片描述



54. OrdersController

在这里插入图片描述



55. IOrderService

在这里插入图片描述



56. OrderServiceImpl

在这里插入图片描述



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

在这里插入图片描述



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

在这里插入图片描述



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

在这里插入图片描述

在这里插入图片描述



订单详情

在这里插入图片描述



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

在这里插入图片描述



2. OrdersController

在这里插入图片描述



3. IOrdersService

在这里插入图片描述



4. OrdersServiceImpl

在这里插入图片描述



5. IOrdersDao

在这里插入图片描述

在这里插入图片描述



6. IMemberDao

在这里插入图片描述



7. ITravellerDao

在这里插入图片描述



用户权限管理

在这里插入图片描述



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过滤器

在这里插入图片描述



7. 创建spring-security.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<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"/>
    
    <!-- 
    	配置具体的规则 
    	auto-config="true"	不用自己编写登录的页面,框架提供默认登录页面
    	use-expressions="false"	是否使用SPEL表达式(没学习过)
    -->
    <security:http auto-config="true" use-expressions="false">
    	<!-- 配置具体的拦截的规则 pattern="请求路径的规则" access="访问系统的人,必须有ROLE_USER的角色" -->
    	<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"/>
    
    <!-- 提供了入门的方式,在内存中存入用户名和密码 
    <security:authentication-manager>
    	<security:authentication-provider>
    		<security:user-service>
    			<security:user name="admin" password="{noop}admin" authorities="ROLE_USER"/>
    		</security:user-service>
    	</security:authentication-provider>
    </security:authentication-manager>
    -->
    
 </beans>   



8. 在web.xml中导入

<!--加载类配置路径-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext.xml,classpath*:spring-security.xml</param-value>
  </context-param>
  <!--配置spring-security过滤器-->
  <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-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. 效果(没有设置权限)

在这里插入图片描述

在这里插入图片描述



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. 执行效果



若登录失败

在这里插入图片描述



  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:password-encoder ref="passwordEncoder"/>-->
        </security:authentication-provider>
    </security:authentication-manager>



登录成功

在这里插入图片描述



从数据库中获取角色



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" />



用户查询

在这里插入图片描述

在这里插入图片描述



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. 效果

在这里插入图片描述



用户添加



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;
    }



用户详情查询

在这里插入图片描述



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);

}



角色查询

在这里插入图片描述



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);



角色详情查询



角色删除



权限管理

在这里插入图片描述



给用户添加角色

在这里插入图片描述



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.annotation</groupId>
            <artifactId>jsr250-api</artifactId>
            <version>1.0</version>
        </dependency>



4) 在web.xml中配置error page

  <error-page>
    <error-code>403</error-code>
    <location>/403.jsp</location>
  </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. 页面端

在这里插入图片描述



1) 导入依赖

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <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">
        <!-- 配置具体的拦截的规则 pattern="请求路径的规则" access="访问系统的人,必须有ROLE_USER的角色" -->
        <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.RequestContextListener</listener-class>
  </listener>



查询日志



版权声明:本文为qq_42530332原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。