001、文档内容介绍
使用 springboot 与 shiro 进行整合使用,实现强大的用户权限管理,其中涉及如何完成用户权限认证(即用户登录),用户授权,thymeleaf 页面整合 shiro 权限标签等知识点。
002、springboot 与 shiro 框架简介
1)springboot:
①由来
spring 的诞生是 Java 企业版的轻量级代替品。无需开发重量级的 EJB,spring 为企业级 Java 开发提供了一种相对简单的方法,通过依赖注入和面向切面编程,用简单的 Java 对象(POJO)实现 EJB 的功能。
但是有以下缺点:
1、配置重量级。
所有 spring 配置都代表了开发时的损耗。因为在思考 spring 特性配置和解决业务问题之间需要进行思维切换,所以写配置挤占了写程序逻辑的时间。
2、项目依赖问题。
1)库与库之间容易产生版本冲突。
2)依赖版本选不对,会有不兼容问题。
由此,引出了 springboot。它简化了基于 spring 的应用开发,只需要 run 就能创建一个独立的,生产级别的 spring 应用。springboot 为 spring 开发及第三方库提供开箱即用的设置(默认设置)。多数的 springboot 应用只需要很少的 spring 配置。
②应用
使用 springboot 创建 java 应用,并使用 java-jar 启动它或者采用传统的 war 部署方式。
2)shiro
apache shiro 是一个强大易用的 java 安全框架,执行身份验证、授权、密码和会话管理。用其易于理解的 api,可以快速、轻松获取任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。
shiro 体系结构
1、Authentication 认证--用户登录
2、Authotization 授权--用户具有哪些权限
3、Cryptography 安全数据加密
4、Session Management 会话管理
5、Web Integration web 系统集成
6、Interations 集成其他应用,spring、缓存框架
1,2 为主要功能,后 3,4,5,6 为附加功能。文档中(只有 1,2)。
003、快速搭建 springboot 项目
1)使用 idea 快速构建 maven 项目。(不再赘述)
2)修改 pom 文件,导入依赖。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>yinheng</groupId>
<artifactId>spring_shiro</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
3)建立启动类
易错点:
不能直接建在 java 包下面,因为此时建立 Application 启动类是不属于任何包的,会报错。
Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package.
4)业务类
5)测试访问
004、项目引入 thymealeaf 页面模板
thymeleaf 在 HTML 页面基础上添加特定标签来实现一下模板渲染。
1)修改 pom,导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2)业务类
3)前端页面
易错点:
html 页面需要放到 resources/templates 文件下,否则找不到文件。会报下面错误:
易错点:
thymeleaf 如果导出的版本问题过低,会造成 html 语法格式要求严谨。(建议直接提升版本为 3.0 以上)
解决:
1)语法书写严格,此处添加 meta 自闭合标签即可。
2)升级版本(推荐使用)。
005、springboot 与 shiro 整合实现用户认证
1)shiro 的核心 API 介绍
subject:用户主体(把操作交给 securityManager)
securityManager:安全管理器(关联 Realm)
Realm:shiro 连接数据的桥梁
数据查询
2)springboot 整合 shiro
①修改pom文件,导入依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>