SpringBoot(二)

模板引擎、数据源、安全框架部分

    • 5、SpringBoot Web开发
      • 5.1、静态资源
      • 5.2、首页
      • 5.3、Thymeleaf模板引擎
      • 5.4、装配扩展SpringMVC
      • 5.5、如何写网站
    • 6、整合JDBC
    • 7、整合Druid数据源
      • 7.1、对druid数据源的相关信息测试
      • 7.2、配置Druid数据源监控
      • 7.3、配置 Druid web 监控 filter 过滤器
    • 8、整合Mybatis
    • 9、SpringSecurity(安全)
      • 9.1、授权
      • 9.2、认证
    • 10、Shiro
      • 10.1、什么是shiro
      • 10.2、组成部分
      • 10.3、Shiro架构(外部)
      • 10.4、Shiro架构(内部)
      • 10.5、快速入门
      • 10.6、springboot与shiro的初步整合
      • 10.7、实现登录拦截
      • 10.8、实现用户认证
      • 10.9、Mybatis整合Shiro
      • 10.10、实现Shiro请求授权
      • 10.11、Thymeleaf整合Shiro
  • ==整合过去整合过来实在是令人头秃,感觉人要废了==

5、SpringBoot Web开发

需要解决的问题:

  • 导入静态资源
  • 首页的问题
  • jsp,模板引擎Thymeleaf
  • 装配扩展SpringMVC
  • 增删改查
  • 拦截器
  • 国际化

5.1、静态资源

web对应的自动配置类:WebMvcAutoConfiguration

方式一:使用webjars的方式

去官网引入webjars的maven依赖

<dependency>
    <groupId>org.webjarsgroupId>
    <artifactId>jqueryartifactId>
    <version>3.4.1version>
dependency>

成功引入之后,启动服务后。访问路径为:localhost:8080/webjars/(我们的资源文件)

方式二:在resource目录下新建文件

ResourceProperties类的部分源码

SpringBoot(二)_第1张图片

即静态资源可以存放的位置为:

  • 新建的public文件夹下
  • 自带的static文件夹下
  • 新建的resources文件夹下
  • 根目录下的/**

外部访问的优先级:resources > static(默认) > public

5.2、首页

源码如图:

SpringBoot(二)_第2张图片

新建一个首页,文件命名为index.html,可以根据适当的需求,自行放在public、static、templates等目录的其中一个下。

访问路径为:localhost:8080

5.3、Thymeleaf模板引擎

对比JSP技术,它是将后端传过来的数据,绑定到对应的形式上,继而达到前端显示后端的数据。Thymeleaf也是将后端传回来的数据与前端的视图进行绑定,达到了与JSP类似的效果(JSP也是一种模板引擎)。Spring Boot推荐使用Thymeleaf模板引擎。

官方网址:https://www.thymeleaf.org

使用Thymeleaf需要导入对应的依赖

html页面可以引入相应相应的xmlns(xml name space):xmlns:th=“http://www.thymeleaf.org”,防止看到报异常看着不舒服

Sping Boot文档中的启动器:

SpringBoot(二)_第3张图片

对应的pom文件

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>

测试案例:

index的控制器类

package pers.mobian.controller;


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class Index {

    @RequestMapping("/index")
    public String index(Model model) {
        model.addAttribute("msg", "hello SpringBoot");
        return "index";
    }
}

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<h1>首页h1>
${msg}
<div th:text="${msg}">div>
body>
html>

执行结果

SpringBoot(二)_第4张图片

总结:当我们访问首页的对应映射后,他会对数据进行封装,然后通过Thymeleaf模板引擎渲染到前端界面。并且前端的接收方式也要变成

Thymeleaf基本语法之:th:eachth:utextth:text

@Controller
public class Index {
    @RequestMapping("/index")
    public String index(Model model) {
        model.addAttribute("msg","

首页

"); model.addAttribute("users", Arrays.asList("mobian1","mobian2","mobian3")); return "index"; } }


<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
	<div th:utext="${msg}">div>
	<div th:text="${msg}">div>
	<div th:each="user:${users}" th:text="${user}">div>
body>
html>

测试结果:

SpringBoot(二)_第5张图片

5.4、装配扩展SpringMVC

测试代码:

package pers.mobian.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Locale;

//如果想要自定义一些功能,只需要重写这个组件,然后将它交给springboot,springboot就会帮我们自动装配
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    //ViewResolver 实现了视图解析器接口的类,我们就可以把它看做视图解析器
    @Bean
    public ViewResolver myViewResolver(){
        return new MyViewResolver();
    }

    //自定义了一个自己的视图解析器MyViewResolver
    public static class MyViewResolver implements ViewResolver{

        @Override
        public View resolveViewName(String viewName, Locale locale) throws Exception {
            return null;
        }
    }
}

补充

package pers.mobian.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Locale;

//如果我们呢要扩展springmvc,官方建议我们这样去做
@Configuration
@EnableWebMvc //这个注解就是导入一个:DelegatingWebMvcConfiguration:从容器中获取所有的webmvcconfig(如果我们自定义了config类就不能添加这个注解)
public class MyMvcConfig implements WebMvcConfigurer {
    //视图跳转
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //访问的url为/mobian,跳转的视图是test.jsp
        registry.addViewController("/mobian").setViewName("test");

    }
}

总结:在springboot中,有非常多的xxxConfiguration帮助我们进行扩展,只要看见这种类,那么它就会改变或者扩展了我们原来spring的功能

5.5、如何写网站

1、搞定前端: 明确页面的样子,方便数据的出现

2、设计数据库(数据库设计是难点)

3、前端能够使其能够自动运行,独立化工程

4、数据接口如何对接:json,对象all in one

5、前后端联调测试

前期准备工作:

  1. 有一套自己数据的后台模板:工作必要!x-amdin
  2. 前端界面:至少自己能够通过前端框架组合出一个网站的页面
    • index
    • about
    • blog
    • post
    • user
  3. 让这个网站能够独立运行

花费一个月的时间去研究


6、整合JDBC

在进行该步操作时,创建的SpringBoot项目需要的依赖为:JDBC API 、MySQL Driver

SpringBoot(二)_第6张图片

导入成功后对应的依赖是

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-jdbcartifactId>
dependency>
<dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
    <scope>runtimescope>
dependency>

由于又是一个web项目,所以还需要添加web的启动器

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-webartifactId>
dependency>

整合案例步骤:

  1. 使用IDEA连接已存在的数据库表

    SpringBoot(二)_第7张图片

  2. 新建application.yaml文件,配置数据库

    spring:
      datasource:
        username: root
        password:
        #注意要配置时区
        url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
        #springboot默认配置的数据库连接使mysql 8.x(虽然我的数据库是5.5,但还是建议使用8.x的)
        #com.mysql.cj.jdbc.Driver mysql 8.x
        #com.mysql.jdbc.Driver mysql 5.x
        driver-class-name: com.mysql.cj.jdbc.Driver
    
  3. 新建一个控制器类JDBCController,处理JDBC的CRUD

    package pers.mobian.controller;
    
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.List;
    import java.util.Map;
    
    @RestController
    public class JDBCController {
        
        /**
         * Spring Boot 默认提供数据源为org.springframework.jdbc.core.JdbcTemplate
         * JdbcTemplate 中会自己注入数据源,用于简化 JDBC操作
         * 还能避免一些常见的错误,使用起来也不用再自己来关闭数据库连接
         */
        @Autowired
        JdbcTemplate jdbcTemplate;
    
        //查找学生
        @RequestMapping("/selectUser")
        public List<Map<String, Object>> selectUser() {
            String sql = "select * from user";
            List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
            return mapList;
        }
    
        //新增学生
        @RequestMapping("/addUser")
        public String addUser() {
            String sql = "insert into mybatis.user(id,name,pwd) values (1,'小明','2222')";
            jdbcTemplate.update(sql);
            return "addUser ok";
        }
    
        //删除学生
        @RequestMapping("/deleteUser/{id}")
        public String deleteUser(@PathVariable("id") int id) {
            String sql = "delete from mybatis.user where id = ? ";
            jdbcTemplate.update(sql, id);
            return "deleteUser ok";
    
        }
    
        //修改学生
        @RequestMapping("/updateUser/{id}")
        public String updateUser(@PathVariable("id") int id) {
            String sql = "update mybatis.user set name=?,pwd=? where id=" + id;
    
            Object[] objects = new Object[2];
            objects[0] = "mobian";
            objects[1] = "88888";
            jdbcTemplate.update(sql, objects);
            return "updateUser ok";
        }
    
    }
    

补充:

在测试类中打印数据源的相关信息

package pers.mobian;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@SpringBootTest
class Springboot04ApplicationTests {

    @Autowired
    DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {

        //查看默认的数据源
        System.out.println(dataSource.getClass());

        //获得数据库连接
        Connection connection = dataSource.getConnection();
        System.out.println(connection);

        //关闭数据库
        connection.close();
    }
}

测试结果:

//我们没有使用其他数据源,springboot就使用默认的数据源,且默认数据源是HikariDataSource
//HikariDataSource 号称 Java WEB 当前速度最快的数据源,相比于传统的 C3P0 、DBCP、Tomcat jdbc 等连接池更加优秀
class com.zaxxer.hikari.HikariDataSource

HikariProxyConnection@1375111241 wrapping com.mysql.cj.jdbc.ConnectionImpl@4eb9ae4d

数据源的所有默认配置类:DataSourceAutoConfiguration


7、整合Druid数据源

Druid 是阿里巴巴开源平台上一个数据库连接池实现,结合了 C3P0、DBCP 等 DB 池的优点,同时加入了日志监控。

Druid 可以很好的监控 DB 池连接和 SQL 的执行情况,天生就是针对监控而生的 DB 连接池。

对应的maven依赖为,由于其日志是使用log4j,所以也需要引入日志对应的依赖

<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>druidartifactId>
    <version>1.1.20version>
dependency>
<dependency>
    <groupId>log4jgroupId>
    <artifactId>log4jartifactId>
    <version>1.2.17version>
dependency>

7.1、对druid数据源的相关信息测试

druid相关的参数

配置 缺省值 说明
name 配置这个属性的意义在于,如果存在多个数据源,监控的时候可以通过名字来区分。如果没有配置,将会生成一个名字,格式是:“DataSource-”+System.identifyHashCode(this)
url 连接数据库的url,不同数据库不一样。例如:mysql:jdbc:mysql://10.20.153.104:3306/druid2 oracle:jdbc:oracle:thin:@10.20.149.85:1521:ocnauto
username 连接数据库的用户名
password 连接数据库的密码。如果你不希望密码直接写在配置文件中,可以使用ConfigFilter
driverClassName 根据url自动识别 这一项可配可不配,如果不配置druid会根据url自动识别dbType,然后选择相应的driverClassName
initialSize 0 初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时
maxActive 8 最大连接池数量
maxldle 8 已经不再使用,配置了也没有效果
minldle 最想连接池数量
maxWait 获取连接时最大等待时间,单位毫秒。配置了maxWait之后,缺省启用公平锁,并发效率有所下降,如果需要可以通过配置useUnfairLock属性为true使用非公平锁
poolPreparedStatements false 是否缓存preparedStatement,也就是PSCache。PSCache对支持游戏的数据库性能提升巨大,比如说oracle。在mysql下建议关闭
maxOpenPreparedStatements -1 要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatement自动出发修改为true。在druid中,不会存在Oracle下PSCache占用内存过多的问题,可以把这个数值配置大一些,比如100
validationQuery 用来检测连接是否有效的sql,要求时一个查询语句。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileldle都不会起作用
validationQueryTimeout 单位秒,检测连接是否有效的超长时间。底层调用jdbcStatement对象的void setQueryTimeout(int seconds)方法
testOnBorrow true 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
testOnReturn false 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
testWhileldle false 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效
timeBetweenEvictionRunsMillis 一分钟 有两个含义:1)Destroy线程会检测连接的间隔时间,如果连接空闲时间大于等于minEvictionRunsMillis则关闭物理连接 2)testWhileldle的判断依据,详情看testWhileldle属性说明
numTestsPerEvictionRun 不再使用,一个DruidDataSource只支持一个EvictionRun
minEvictableldleTimeMillis 30分钟 连接保持空闲而不被驱逐的最长时间
connectionInitSqls 物理连接初始化的时候执行的sql
exceptionSorter 根据dbType自动识别 当数据库抛出一些不可恢复的异常时,抛弃连接
filters 属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有:监控统计用的filter:start日志用的filter:log4j 防御sql注入的filter:wall
proxyFilters 类型是List如果配置了filters和proxyFilters,是组合关系,而非替换关系

在springboot启动类的统计目录下新建一个配置配:

@Configuration
public class DruidConfig {
    /*
       将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建
       绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效
       @ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中
       前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }
}

测试类:

@SpringBootTest
class Springboot04ApplicationTests {

    @Autowired
    DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {

        //查看默认的数据源
        System.out.println(dataSource.getClass());

        //获得数据库连接
        Connection connection = dataSource.getConnection();
        System.out.println(connection);

        DruidDataSource druidDataSource = (DruidDataSource) dataSource;
        System.out.println("druidDataSource 数据源最大连接数:" + druidDataSource.getMaxActive());
        System.out.println("druidDataSource 数据源初始化连接数:" + druidDataSource.getInitialSize());

        //关闭数据库
        connection.close();
    }
}

测试结果:

class com.alibaba.druid.pool.DruidDataSource
2020-03-17 20:56:55.105  INFO 10448 --- [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
com.mysql.cj.jdbc.ConnectionImpl@25ce435
druidDataSource 数据源最大连接数:8
druidDataSource 数据源初始化连接数:0

在yaml核心配置文件中进行相应设置后

spring:
  datasource:
    username: root
    password:
    #?serverTimezone=UTC解决时区的报错
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

    #Spring Boot 默认是不注入这些属性值的,需要自己绑定
    #druid 数据源专有配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true

    #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
    #如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority
    #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

再次测试结果:

class com.alibaba.druid.pool.DruidDataSource
log4j:WARN No appenders could be found for logger (druid.sql.Connection).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
2020-03-17 20:59:36.003  INFO 1964 --- [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@4cb00fa5
druidDataSource 数据源最大连接数:20
druidDataSource 数据源初始化连接数:5 //在配置文件中进行了修改

7.2、配置Druid数据源监控

Druid 数据源具有监控的功能,并提供了一个 web 界面方便用户查看,类似安装 路由器 时,人家也提供了一个默认的 web 页面

对应的配置类

package pers.mobian.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidConfig {

    /*
       将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建
       绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效
       @ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中
       前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }


    //配置 Druid 监控管理后台的Servlet;
//内置 Servlet 容器时没有web.xml文件,所以使用 Spring Boot 的注册 Servlet 方式
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");

        // 这些参数可以在 com.alibaba.druid.support.http.StatViewServlet
        // 的父类 com.alibaba.druid.support.http.ResourceServlet 中找到
        Map<String, String> initParams = new HashMap<>();
        initParams.put("loginUsername", "admin"); //后台管理界面的登录账号
        initParams.put("loginPassword", "123456"); //后台管理界面的登录密码

        //后台允许谁可以访问
        //initParams.put("allow", "localhost"):表示只有本机可以访问
        //initParams.put("allow", ""):为空或者为null时,表示允许所有访问
        initParams.put("allow", "");
        //deny:Druid 后台拒绝谁访问
        //initParams.put("kuangshen", "192.168.1.20");表示禁止此ip访问

        //设置初始化参数
        bean.setInitParameters(initParams);
        return bean;
    }
}

在url中访问:http://localhost:8080/druid 它会自动跳转到http://localhost:8080/druid/login.html

SpringBoot(二)_第8张图片

在正确输入用户名和密码后,可以进入到其对应的后台。当用户进行了相关操作以后,其后台就会打印与其相关的信息。(此截图为我新开的一个界面,执行了相应的映射语句后,该监控后台打印出我的操作的sql语句)

SpringBoot(二)_第9张图片

7.3、配置 Druid web 监控 filter 过滤器

//配置 Druid 监控 之  web 监控的 filter
//WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计
@Bean
public FilterRegistrationBean webStatFilter() {
    FilterRegistrationBean bean = new FilterRegistrationBean();
    bean.setFilter(new WebStatFilter());

    //exclusions:设置哪些请求进行过滤排除掉,从而不进行统计
    Map<String, String> initParams = new HashMap<>();
    initParams.put("exclusions", "*.js,*.css,/druid/*,/jdbc/*");
    bean.setInitParameters(initParams);

    //"/*" 表示过滤所有请求
    bean.setUrlPatterns(Arrays.asList("/*"));
    return bean;
}

8、整合Mybatis

在进行该步操作时,创建的SpringBoot项目需要的依赖是:JDBC API 、MySQL Driver

还需要引入springboot与mybatis相关联的依赖


<dependency>
    <groupId>org.mybatis.spring.bootgroupId>
    <artifactId>mybatis-spring-boot-starterartifactId>
    <version>2.1.1version>
dependency>

由于需要启动web服务,所以还需要引入web的启动器

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-webartifactId>
dependency>

为了代码方便引入lombok插件依赖

<dependency>
    <groupId>org.projectlombokgroupId>
    <artifactId>lombokartifactId>
    
    <version>1.18.8version>
    <scope>providedscope>
dependency>

整合案例步骤:

1、连接数据库

spring:
  datasource:
    username: root
    password:
    #?serverTimezone=UTC解决时区的报错
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    
#此处配置文件可以当作mybatis的配置类,可以配置实体类的别名,以及映射文件的位置
mybatis:
  type-aliases-package: pers.mobian.pojo #别名
  mapper-locations: mapper/*.xml #mapper类的位置,mybatis配置类中的绑定mapper语句

2、编写对应的实体类

package pers.mobian.pojo;


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private int id;
    private String pwd;
}

3、编写对应的接口类

package pers.mobian.mapper;

import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import pers.mobian.pojo.User;

import java.util.List;

@Repository
@Mapper
public interface UserMapper {

    //查询所有的用户
    List<User> selectUser();

    //根据id查询用户
    User selectUserById(int id);

    //添加用户
    public int insertUser(User user);

    //删除用户
    public int deleteUser(int id);

    //修改用户
    public int updateUser(User user);
}

4、编写对应的接口的mapper类

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="pers.mobian.mapper.UserMapper">

    <select id="selectUser" parameterType="pers.mobian.pojo.User" resultType="pers.mobian.pojo.User">
        select * from mybatis.user
    </select>

    <select id="selectUserById" resultType="pers.mobian.pojo.User">
        select * from mybatis.user where id=#{id}

    </select>

    <insert id="insertUser" parameterType="pers.mobian.pojo.User">
        insert into mybatis.user (name,id,pwd) values (#{name},#{id},#{pwd})
    </insert>

    <delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id=#{id}
    </delete>

    <update id="updateUser" parameterType="pers.mobian.pojo.User">
        update mybatis.user set name=#{name},id=#{id},pwd=#{pwd} where id=#{id}
    </update>

</mapper>

5、对应的控制器类

package pers.mobian.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import pers.mobian.mapper.UserMapper;
import pers.mobian.pojo.User;

import java.util.List;

@RestController
public class UserTest {

    //自动装配UserMapper
    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/selectUser")
    public List<User> selectUserTest() {
        List<User> userList = userMapper.selectUser();
        for (User user : userList) {
            System.out.println(user);
        }
        return userList;
    }

    @RequestMapping("/selectUser/{id}")
    public User selectUserById(@PathVariable("id") int id) {
        User user = userMapper.selectUserById(id);
        System.out.println(user);
        return user;
    }

    @RequestMapping("/insertUser")
    public String insertUser() {
        userMapper.insertUser(new User("王二小", 1, "999"));
        return "insertUser ok";
    }

    @RequestMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id") int id) {
        userMapper.deleteUser(id);
        return "deleteUser ok";
    }

    @RequestMapping("/updateUser")
    public String updateUser(){
        userMapper.updateUser(new User("王三小",1,"jjjj"));
        return  "updateUser ok";
    }
}

注意:接口类与其的对应的mapper类如果没有在同一目录下,则在yaml核心配置文件中需要进行相应的绑定。类似于曾经mybatis-config配置文件中定位资源文件。


9、SpringSecurity(安全)

基于AOP技术的安全

属于非功能性需求,但应在设计之初就考虑

Spring Security是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,它可以实现强大的Web安全控制,对于安全控制,我们仅需要引入spring-boot-starter-security模块,进行少量的配置,即可实现强大的安全管理

需要记忆的几个类:

  • WebSecurityConfigurerAdapter:自定义Security策略
  • AuthenticationMangerBuilder:自定义认证策略
  • @EnableWebSecurity:开启WebSecurity模式

Spring Security的两个主要目标是“认证”和“授权”(控制访问)

认证:Authentication

授权:Authorization

这是两个通用的概念,不仅仅在Spring Security中存在

9.1、授权

  1. 重写configure(HttpSecurity http)方法

  2. http.xxx可以设置相应的权限规则

  3. Spring Security拥有自己定制的登录界面,如果需要使用自己的,要进行相应的设置

  4. 还可以自己开启相关的操作,如:记住次此会话(cookie,默认保存两周)、注销功能、开启csrf防止网站被恶意攻击

9.2、认证

  1. 重写configure(AuthenticationManagerBuilder auth)方法
  2. aun.xx,可以读取数据库或者内存中的数据,用来判断用户的访问权限级别
  3. 对于密码, 需要使用到加密算法(如果不使用加密算法,代码被反编译能够看到最初的代码)

10、Shiro

10.1、什么是shiro

  • Apache Shiro是一个java的安全(权限)框架
  • Shiro可以非常容易地开发出足够好地应用,其不仅可以在JavaSEE环境,也可以使用在JavaEE环境中
  • Shiro可以完成,认证,授权,加密,会话管理,Web集成,缓存等
  • 官网:http://shiro.apache.org

10.2、组成部分

  • Authentication:身份认证、登录,验证用户是不是拥有相应地身份
  • Authorization:授权,即权限验证,验证某个已认证地用户是否拥有某个权限,即判断用户能否进行有关操作。如:验证某个用户是否拥有某个角色,或者细粒度的验证某个用户对某个资源是否具有某个权限
  • Session Manger:会话管理,即用户登录后就是第一次会话,在内有退出之前,它的所有信息都在会话中;会话可以是普通的JavaSE环境,也可以是Web环境
  • Cryptography:加密,保护数据的安全,如密码加密存储到数据库中,而不是明文存储
  • Web Support:Web支持,可以非常容易集成到Web环境
  • Caching:缓存,比如用户登录后,其用户信息,拥有的角色、权限不必每一次都去查看,这样可以提高效率
  • Concurrency:Shiro支持多线程应用的并发验证,如,在一个线程中开启另一个线程,能把权限自动的传播过去
  • Testing:提供测试支持
  • Run As:允许一个用户假装为另一个用户(如果他们允许)的身份进行访问
  • Remember Me:记住我,这是一个非常常见的功能,即一次登录后,下次再来就不需要登陆

10.3、Shiro架构(外部)

SpringBoot(二)_第10张图片

  • subject:应用代码直接交互的对象是Subject,也就是说Shiro的对外API核心就是Subject,Subject代表了当前的用户,这个用户不一定是一个具体的人,与当前应用交互的任何东西都是subject,如网络爬虫,机器人等,与Subject的所有交互都会委托给SecurityManager;Subject其实是一个门面,SecurityManageer才是实际的执行者
  • SecurityManager:安全管理器,即多有与安全有关的操作都会与SecurityManager交互,并且它管理着所有的Subject,可以看出它是Shiro的核心,它负责与Shiro的其他组件进行交互,它相当于SpringMVC的DispatchServlet的角色
  • Realm:Shiro从Realm获取安全数据(如用户,角色,权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较,来确定用户的身份是否合法;也需要从Realm得到用户相应的角色、权限,进行验证用户的操作是否能够进行,可以把Realm堪称DataSource

10.4、Shiro架构(内部)

SpringBoot(二)_第11张图片

  • Subject:任何可以与应用交互的用户
  • Security Manager:相当于SpringMVC中的DispatchServlet;是Shiro的心脏,所有具体的交互都通过Security Manager进行控制,它管理着所有的Subject,且负责进行认证,授权,会话,以及缓存管理。
  • Authenticator:负责Subject认证,是一个扩展点,可以自定义实现;可以使用认证策略(Authentication Strategy),即什么情况下算用户认证通过了
  • Authorizer:授权器,即访问控制器,用来决定主体是否有权限进行相应的操作;即控制着用户能访问应用中的那些功能
  • Realm:可以有一个或者多个的realm,可以认为是安全实体数据源,即用于获取安全实体的,可以用JDBC实现,也可以是内存实现等等,由用户提供;所以一般在应用中都需要实现自己的realm
  • SessionManager:管理Session生命周期的组件,而Shiro并不仅仅可以用在Web环境,也可以用在普通的JavaSE环境中
  • CacheManager:缓存控制器,来管理用户,角色,权限等缓存;因为这些数据基本上很少改变,放到缓存中后可以提高访问的性能
  • Cryptography:密码模块,Shiro提高了一些常见的加密组件用于密码加密,解密等

10.5、快速入门

1、导入依赖


<dependency>
    <groupId>org.apache.shirogroupId>
    <artifactId>shiro-coreartifactId>
    <version>1.4.2version>
dependency>

<dependency>
    <groupId>org.slf4jgroupId>
    <artifactId>jcl-over-slf4jartifactId>
    <version>1.7.21version>
    <scope>runtimescope>
dependency>
<dependency>
    <groupId>org.slf4jgroupId>
    <artifactId>slf4j-log4j12artifactId>
    <version>1.7.21version>
    <scope>runtimescope>
dependency>
<dependency>
    <groupId>log4jgroupId>
    <artifactId>log4jartifactId>
    <version>1.2.17version>
    <scope>runtimescope>
dependency>

2、在resource目录下新建log4j.properties

log4j.rootLogger=INFO, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n

# General Apache libraries
log4j.logger.org.apache=WARN

# Spring
log4j.logger.org.springframework=WARN

# Default Shiro logging
log4j.logger.org.apache.shiro=INFO

# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN

3、在resource目录下新建shiro.ini

[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz

# -----------------------------------------------------------------------------
# Roles with assigned permissions
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5

4、新建一个快速的开始类Quickstart

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * Simple Quickstart application showing how to use Shiro's API.
 *
 * @since 0.9 RC2
 */
public class Quickstart {

    private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);


    public static void main(String[] args) {


        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);



        // get the currently executing user:
        //获得当前的用户对象Subject
        Subject currentUser = SecurityUtils.getSubject();

        // Do some stuff with a Session (no need for a web or EJB container!!!)
        //通过当前的用户对象拿到Session
        Session session = currentUser.getSession();
        session.setAttribute("someKey", "aValue");
        String value = (String) session.getAttribute("someKey");
        if (value.equals("aValue")) {
            log.info("Retrieved the correct value! [" + value + "]");
        }

        // let's login the current user so we can check against roles and permissions:
        //判断当前用户是否被认证
        if (!currentUser.isAuthenticated()) {

            //Token:令牌,随机
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            token.setRememberMe(true);//设置记住我
            try {
                currentUser.login(token);//执行登录操作
            } catch (UnknownAccountException uae) {
                log.info("There is no user with username of " + token.getPrincipal());
            } catch (IncorrectCredentialsException ice) {
                log.info("Password for account " + token.getPrincipal() + " was incorrect!");
            } catch (LockedAccountException lae) {
                log.info("The account for username " + token.getPrincipal() + " is locked.  " +
                        "Please contact your administrator to unlock it.");
            }
            // ... catch more exceptions here (maybe custom ones specific to your application?
            catch (AuthenticationException ae) {
                //unexpected condition?  error?
            }
        }

        //say who they are:
        //print their identifying principal (in this case, a username):
        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

        //test a role:
        if (currentUser.hasRole("schwartz")) {
            log.info("May the Schwartz be with you!");
        } else {
            log.info("Hello, mere mortal.");
        }

        //test a typed permission (not instance-level)
        //粗粒度
        if (currentUser.isPermitted("lightsaber:wield")) {
            log.info("You may use a lightsaber ring.  Use it wisely.");
        } else {
            log.info("Sorry, lightsaber rings are for schwartz masters only.");
        }

        //a (very powerful) Instance Level permission:
        //细粒度
        if (currentUser.isPermitted("winnebago:drive:eagle5")) {
            log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
                    "Here are the keys - have fun!");
        } else {
            log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
        }

        //all done - log out!
        //注销
        currentUser.logout();

        //结束
        System.exit(0);
    }
}

执行结果:

2020-03-18 15:43:58,561 INFO [org.apache.shiro.session.mgt.AbstractValidatingSessionManager] - Enabling session validation scheduler... 
2020-03-18 15:43:59,783 INFO [Quickstart] - Retrieved the correct value! [aValue] 
2020-03-18 15:43:59,787 INFO [Quickstart] - User [lonestarr] logged in successfully. 
2020-03-18 15:43:59,787 INFO [Quickstart] - May the Schwartz be with you! 
2020-03-18 15:43:59,788 INFO [Quickstart] - You may use a lightsaber ring.  Use it wisely. 
2020-03-18 15:43:59,788 INFO [Quickstart] - You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  Here are the keys - have fun! 

核心要点:

Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
currentUser.isAuthenticated()
currentUser.hasRole("schwartz")
currentUser.isPermitted("lightsaber:wield")
currentUser.logout();
currentUser.getPrincipal()

10.6、springboot与shiro的初步整合

1、新建一个带web依赖的springboot项目

2、引入外部依赖:shiro-spring与thymeleaf模板引擎需要的依赖

<dependency>
    <groupId>org.apache.shirogroupId>
    <artifactId>shiro-springartifactId>
    <version>1.4.2version>
dependency>

<dependency>
    <groupId>org.thymeleafgroupId>
    <artifactId>thymeleaf-spring5artifactId>
dependency>
<dependency>
    <groupId>org.thymeleaf.extrasgroupId>
    <artifactId>thymeleaf-extras-java8timeartifactId>
dependency>

3、在配置包下新建UserRealm类

package pers.mobian.config;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class UserRealm extends AuthorizingRealm {


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了=> 授权doGetAuthorizationInfo");
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=> 认证doGetAuthenticationInfo");
        return null;
    }
}

4、在配置包下新建ShiroConfig类

package pers.mobian.config;

import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {


    //创建ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultSecurityManager defaultSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultSecurityManager);
        return bean;
    }


    //创建DefaultSecurityManager
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联userRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //创建realm对象, 需要自定义类
    @Bean
    public UserRealm userRealm() {
        return new UserRealm();
    }
}

5、新建控制器类IndexController

package pers.mobian.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {

    @RequestMapping({"/", "/index"})
    public String indexTest(Model model) {
        model.addAttribute("msg", "hello springboot-shiro");
        return "index";
    }


    @RequestMapping("/user/add")
    public String addTest(){
        return "/user/add";
    }

    @RequestMapping("/user/update")
    public String updateTest(){
        return "/user/update";
    }
}

6、在templates目录下编写html界面


<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<h1>首页h1>

<p th:text="${msg}">p>

<a th:href="@{/user/add}">adda>|<a th:href="@{/user/update}">updatea>
body>
html>

7、在templates下新建user目录,并建立add.html和update.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Title</title>
</head>
<body>
	<h1>add</h1>
</body>
</html>



<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Title</title>
</head>
<body>
	<h1>update</h1>
</body>
</html>

8、测试结果

SpringBoot(二)_第12张图片

10.7、实现登录拦截

1、修改ShiroConfig类

package pers.mobian.config;

import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {


    //创建ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultSecurityManager defaultSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultSecurityManager);

        //添加shiro的内置过滤器
         /*
        anno:无需认证就可以访问
        authc:必须认证了才能通过
        user:必须拥有记住我这个功能才能使用
        perms:拥有对某个资源的权限才能访问
        role:拥有某个角色权限才能访问
        */

        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/user/*","authc");
        bean.setFilterChainDefinitionMap(filterMap);

        //设置登录的请求
        bean.setLoginUrl("/toLogin");
        return bean;
    }


    //创建DefaultSecurityManager
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联userRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //创建realm对象, 需要自定义类
    @Bean
    public UserRealm userRealm() {
        return new UserRealm();
    }
}

2、新建一个登录界面


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<form action="">
    <p>用户名:<input type="text" name="username">p>
    <p>密码:<input type="password" name="password">p>
    <p><input type="submit">p>
form>
body>
html>

3、添加对应的映射

@RequestMapping("/toLogin")
public String toLogin(){
    return "login";
}

测试点击对应的方法,会跳转到登录界面

10.8、实现用户认证

1、在控制器类中添加对应的代码

@RequestMapping("/login")
public String login(String username, String password, Model model) {
    Subject subject = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(username, password);

    try {
        subject.login(token);
        return "index";
    } catch (UnknownAccountException e) {
        model.addAttribute("msg", "用户名错误");
        return "login";
    } catch (IncorrectCredentialsException e) {
        model.addAttribute("msg", "密码错误");
        return "login";
    }
}

2、修改UserRealm

package pers.mobian.config;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class UserRealm extends AuthorizingRealm {


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了=> 授权doGetAuthorizationInfo");
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=> 认证doGetAuthenticationInfo");

        //用户名,密码,来自于数据库中取出,此处伪造数据
        String name="root";
        String password = "123456";
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        if(!userToken.getUsername().equals(name)){
            return null;//抛出异常 UnknownAccountException(控制器中定义的异常)
        }

        //密码认证,shiro自己内部操作
        return new SimpleAuthenticationInfo("",password,"");
    }
}

3、此时即可完成用户身份的校验

每次登录的时候,系统都会去通过控制器类然后跳转到UserRealm类,继而进行用户名和密码的判断。

10.9、Mybatis整合Shiro

1、引入对应的maven依赖

<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>druidartifactId>
    <version>1.1.20version>
dependency>
<dependency>
    <groupId>log4jgroupId>
    <artifactId>log4jartifactId>
    <version>1.2.17version>
dependency>
<dependency>
    <groupId>org.projectlombokgroupId>
    <artifactId>lombokartifactId>
    <version>1.18.8version>
dependency>
<dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
    <version>8.0.16version>
dependency>

<dependency>
    <groupId>org.mybatis.spring.bootgroupId>
    <artifactId>mybatis-spring-boot-starterartifactId>
    <version>2.1.1version>
dependency>

<dependency>
    <groupId>org.apache.shirogroupId>
    <artifactId>shiro-springartifactId>
    <version>1.4.2version>
dependency>

2、新建核心配置文件application.yaml,用来配置数据源(可以自行选择添加与否)并且配置mybatis信息

spring:
  datasource:
    username: root
    password:
    #?serverTimezone=UTC解决时区的报错
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

    #Spring Boot 默认是不注入这些属性值的,需要自己绑定
    #druid 数据源专有配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true

    #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
    #如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority
    #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500


mybatis:
  type-aliases-package: pers.mobian.pojo
  mapper-locations: classpath:mapper/*.xml

3、新建实体类

package pers.mobian.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private int id;
    private String pwd;
}

4、新建mapper的接口类

package pers.mobian.mapper;

import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import pers.mobian.pojo.User;

@Mapper
@Repository
public interface UserMapper {

    public User queryUserByName(String name);
}

5、新建mapper接口类的实体类



<mapper namespace="pers.mobian.mapper.UserMapper">
    <select id="queryUserByName" parameterType="String" resultType="User">
        select * from mybatis.user where name=#{name}
    select>
mapper>

6、编写对应的service层接口类

package pers.mobian.service;

import pers.mobian.pojo.User;

public interface UserService {
    public User queryUserByName(String name);
}

7、编写对应的service层接口类的实现类

package pers.mobian.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.mobian.mapper.UserMapper;
import pers.mobian.pojo.User;

@Service
public class UserServiceImpl implements  UserService{

    @Autowired
    UserMapper userMapper;

    @Override
    public User queryUserByName(String name) {
        return userMapper.queryUserByName(name);
    }
}

8、控制器类代码不变

@RequestMapping("/login")
public String login(String username, String password, Model model) {
    Subject subject = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(username, password);

    try {
        subject.login(token);
        return "index";
    } catch (UnknownAccountException e) {
        model.addAttribute("msg", "用户名错误");
        return "login";
    } catch (IncorrectCredentialsException e) {
        model.addAttribute("msg", "密码错误");
        return "login";
    }
}

9、ShiroConfig类不变

package pers.mobian.config;

import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {


    //创建ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultSecurityManager defaultSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultSecurityManager);

        //添加shiro的内置过滤器
         /*
        anno:无需认证就可以访问
        authc:必须认证了才能通过
        user:必须拥有记住我这个功能才能使用
        perms:拥有对某个资源的权限才能访问
        role:拥有某个角色权限才能访问
        */

        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/user/*","authc");
        bean.setFilterChainDefinitionMap(filterMap);

        //设置登录的请求
        bean.setLoginUrl("/toLogin");
        return bean;
    }


    //创建DefaultSecurityManager
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联userRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //创建realm对象, 需要自定义类
    @Bean
    public UserRealm userRealm() {
        return new UserRealm();
    }
}

10、将UserRealm类中的模拟数据变成真实的数据库数据

package pers.mobian.config;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import pers.mobian.pojo.User;
import pers.mobian.service.UserService;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了=> 授权doGetAuthorizationInfo");
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=> 认证doGetAuthenticationInfo");
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        //连接真实的数据库
        User user = userService.queryUserByName(userToken.getUsername());
        if(user == null) { //数据库中没有查询到该用户
            return null;
        }

        //md5加密:一串数字
        //md5盐值加密:一串数字加上用户名
        //密码认证,shiro自己操作
        return new SimpleAuthenticationInfo("",user.getPwd(),"");
    }
}

11、对应的目录结构是

SpringBoot(二)_第13张图片

12、测试代码即可完成安全验证

10.10、实现Shiro请求授权

type=Unauthorized,status=401

1、修改数据库的字段并且修改pojo类

SpringBoot(二)_第14张图片

2、修改ShiroConfig类

package pers.mobian.config;

import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {


    //创建ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultSecurityManager defaultSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultSecurityManager);

        //添加shiro的内置过滤器
         /*
        anno:无需认证就可以访问
        authc:必须认证了才能通过
        user:必须拥有记住我这个功能才能使用
        perms:拥有对某个资源的权限才能访问
        role:拥有某个角色权限才能访问
        */

         //拦截
        Map<String, String> filterMap = new LinkedHashMap<>();
        //授权,正常情况下,没有授权会跳转到未授权页面
        filterMap.put("/user/add","perms[user:add]");
        filterMap.put("/user/update","perms[user:update]");


        filterMap.put("/user/*","authc");
        bean.setFilterChainDefinitionMap(filterMap);

        //设置登录的请求
        bean.setLoginUrl("/toLogin");

        //未授权的页面
        bean.setUnauthorizedUrl("/unauthorized");
        return bean;
    }


    //创建DefaultSecurityManager
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联userRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //创建realm对象, 需要自定义类
    @Bean
    public UserRealm userRealm() {
        return new UserRealm();
    }
}

3、修改UserRealm类

package pers.mobian.config;

import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import pers.mobian.pojo.User;
import pers.mobian.service.UserService;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了=> 授权doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission("user:add");

        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        //拿到User对象
        User currentUser = (User) subject.getPrincipal();

        //设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=> 认证doGetAuthenticationInfo");
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        //连接真实的数据库
        User user = userService.queryUserByName(userToken.getUsername());
        if(user == null) { //数据库中没有查询到该用户
            return null;
        }

        //md5加密:一串数字
        //md5盐值加密:一串数字加上用户名
        //密码认证,shiro自己操作
        return new SimpleAuthenticationInfo("user",user.getPwd(),"");
    }
}

此案例能够达到不同的用户对同一个页面拥有不同的权限

10.11、Thymeleaf整合Shiro

目的:将Shiro与前端的模板引擎Thymeleaf整合,达到不同权限不同显示的效果

1、修改index.html界面


<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"
      xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<h1>首页h1>

<div th:if="${session.loginUser==null}">
    <a th:href="@{/toLogin}">登录a>
div>

<p th:text="${msg}">p>

<div shiro:hasPermission="user:add">
    <a th:href="@{/user/add}">adda>
div>
<div shiro:hasPermission="user:update">
    <a th:href="@{/user/update}">updatea>
div>

body>
html>

2、将前端需要的session放在UserRealm类中

package pers.mobian.config;

import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import pers.mobian.pojo.User;
import pers.mobian.service.UserService;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了=> 授权doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission("user:add");

        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        //拿到User对象
        User currentUser = (User) subject.getPrincipal();

        //设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=> 认证doGetAuthenticationInfo");
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        //连接真实的数据库
        User user = userService.queryUserByName(userToken.getUsername());
        if(user == null) { //数据库中没有查询到该用户
            return null;
        }


        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",user);


        //md5加密:一串数字
        //md5盐值加密:一串数字加上用户名
        //密码认证,shiro自己操作
        return new SimpleAuthenticationInfo("user",user.getPwd(),"");
    }
}

整合过去整合过来实在是令人头秃,感觉人要废了

你可能感兴趣的:(自学知识笔记)