10_SpringBoot


目录
  • 一. 原理初探
    • 1.1 自动装配
      • 1.1.1 pom.xml
      • 1.1.2 启动器
      • 1.1.3 主程序
      • 1.1.4 配置文件
  • 二. YAML
    • 2.1 语法示例
    • 2.2 为属性赋值的三种方式
      • 2.2.1 不使用配置文件
      • 2.2.2 使用配置文件 application.yaml [推荐]
      • 2.2.3 使用自定义配置文件xxx..properties
      • 补充1: 消除爆红提示
      • 补充2: 解析LocalDate
      • 补充3: 设置编码格式
      • 补充4: JSR303数据校验
      • 补充5: 热加载
      • 2.2.4 结论
  • 三. 配置文件优先级和多环境配置
    • 3.1 application.yaml生效优先级
    • 3.2 多环境配置
    • 3.3 自动装配原理
  • 四. SpringBoot web开发
    • 4.1 静态资源导入探究
    • 4.2 首页和图标定制
    • 4.3 SpringMVC配置
      • 4.3.1 扩展SpringMVC方法一
      • 4.3.2 扩展SpringMVC方法二[推荐]
  • 五. 员工管理系统
    • 5.1 导入静态资源
    • 5.2 首页实现
    • 5.3 国际化
  • 六. 整合druid, MyBatis, log4j
    • 6.1 导入依赖
    • 6.2 编写实体类
    • 6.3 编写实体类接口
    • 6.4 准备Mapper映射文件
    • 6.5 添加yaml文件配置信息
      • 6.5.1 MyBatis配置
      • 6.5.2 连接数据库配置
    • 6.6 编写log4j配置文件
    • 6.7 编写DruidConfig配置类
  • 七. SpringSecurity
    • 7.1 导入依赖
    • 7.2 编写SecurityConfig
    • 7.3 编写Controller
    • 7.4 login.html
    • 7.5 index.html
  • 八. Shiro
    • 8.1 导入依赖
    • 8.2 编写Realm
    • 8.3 编写ShiroConfig配置类
    • 8.4 log4j

一. 原理初探

1.1 自动装配

1.1.1 pom.xml
  • spring-boot-dependencies: 核心依赖在父工程中
  • 我们在写入或者引入一些SpringBoot依赖的时候, 不需要指定版本, 就是因为有这些版本仓库
1.1.2 启动器
  • 
        org.springframework.boot
        spring-boot-starter
    
    
  • 启动器: 说白了就是SpringBoot的启动场景;

  • 比如spring-boot-starter-web, 它就会帮我们导入web环境所有的依赖

  • SpringBoot会将所有的功能场景, 都变成一个个的启动器

  • 我们要使用什么功能, 就只需找到对应的启动器就可以了 starter

1.1.3 主程序
//标注这个类是一个SpringBoot的应用
@SpringBootApplication
public class SpringbootStudyApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootStudyApplication.class, args);
    }

}
  • 注解

    • @SpringBootConfiguration: SpringBoot的配置
      	@Configuration: Spring配置类
      		@Component: 说明这也是Spring的一个组件
      
      @EnableAutoConfiguration: 自动配置
      	@AutoConfigurationPackage: 自动配置包
      		@Import({Registrar.class}): 导入注册类
      	@Import({AutoConfigurationImportSelector.class}): 自动配置导入选择器
      	 
      
1.1.4 配置文件
  • SpringBoot使用一个全局的配置文件, 配置文件的名称是固定的
    • application.properties
      • 语法结构: key=value
    • application.yaml
      • 语法结构: key: 空格 value

配置文件的作用: 修改SpringBoot自动配置的默认值, 因为SpringBoot在底层都给我们自动配置好了

二. YAML

2.1 语法示例

#对空格要求很严格 冒号后要加一个空格

#普通的key: value
name: 张三

#对象
student:
	name: 张三
	age: 18
	
#行内写法
student: {name: 张三,age: 18}

#数组
pet:
	- cat
	- dog
	- pig

#行内写法
pet: [cat,dog,pig]

2.2 为属性赋值的三种方式

2.2.1 不使用配置文件
  • 传统的注解方式 @Component + @Value

  • @Component
    public class Person {
    	@Value("张三")
        private String name;
        //省略...
    }
    
2.2.2 使用配置文件 application.yaml [推荐]
  • 使用注解@Component + @ConfigurationProperties(prefix = "person")的方式, 把.yaml配置文件中的属性映射到这个组件中, prefix = "person" 表示将配置文件中person下的所有属性一一对应 [推荐]

  • @Component
    @ConfigurationProperties(prefix = "person")
    public class Person {
    
        private String name;
        private Integer age;
        private Boolean happy;
        private Date birth;
        private Map map;
        private List list;
        private Dog dog;
    	
        //Getter and Setter
    }
    
    
    
  • #yaml配置文件
    #key: value 冒号后面要有一个空格
    #对空格要求很严格
    person:
      name: 张三
      age: 18
      happy: false
      birth: 2000/01/01
      map: {k1: v1,k2: v2}
      list: [code,music,girl]
      dog:
        name: 小黑
        age: 2
    
  • 2.2.3 使用自定义配置文件xxx..properties
    • 使用注解@Component + @PropertySource(value = "classpath:zhangsan.properties")绑定自定义的.properties文件, 然后需要在实体类中的属性上方使用SPEL表达式取出配置文件的值比如 @Value("${name}"), 比较麻烦

    • @Component
      @PropertySource(value = "classpath:zhangsan.properties")
      public class Person {
      
          @Value("${name}")
          private String name;
          //省略...
      }
      
    补充1: 消除爆红提示
    • 使用@ConfigurationProperties时, idea会弹出一个红色提示, 但不会影响程序的运行, 如果想要消除红色区域, 需要导入pom.xml一个依赖
    
        org.springframework.boot
        spring-boot-configuration-processor
        true
    
    
    补充2: 解析LocalDate
    • 假如实体类中的属性为LocalDate时, 需要在属性上方使用注解@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)来解析.yaml配置文件中的 2020-02-02 格式的日期
    @Component
    @ConfigurationProperties(prefix = "dog")
    public class Dog {
       
        private String name;
        private Integer age;
        @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
        private LocalDate birth;
        //省略...
    }
    
    #yaml
    dog: {name: 小黄,age: 2,birth: 2020-01-01}
    
    补充3: 设置编码格式
    • 如果我们使用的是properties配置文件, 需要设置idea编码格式为UTF-8, idea中默认的编码格式为GBK, 修改为UTF-8以防止乱码

    • Settings > Editor > File Encoding中把所有的编码格式改为UTF-8, 最后一个可以打钩

    补充4: JSR303数据校验
    • JSR303数据校验, 这个就是我们可以在字段上增加一层过滤器验证, 可以保证数据的合法性

    • 需要导入依赖到pom.xml中

    
        org.springframework.boot
        spring-boot-starter-validation
    
    

    类上方使用注解@Validated 开启数据校验

    @Component
    @ConfigurationProperties(prefix = "person")
    @Validated //数据校验
    public class Person {
    
        @Email(message = "邮箱格式错误!")
        private String name;
        //省略...
    }
    
    补充5: 热加载
    • 导入依赖
    
    	org.springframework.boot
    	spring-boot-devtools
    	true
    
    
    • 修改IDEA设置 Settings > Build,Execution > Compiler > 勾选Build project automatically
    • 之后项目修改后,只需Build一下即可,无需重新部署项目
    2.2.4 结论
    • 配置yaml和配置properties都可以获取到值, 强烈推荐yaml
    • 如果我们在某个业务中, 只需要获取配置文件中的某个值, 可以使用一下@Value
    • 但如果我们专门编写了一个JavaBean来和配置文件进行映射, 就直接使用@ConfigurationProperties, 不要犹豫

    三. 配置文件优先级和多环境配置

    3.1 application.yaml生效优先级

    1. file:./config/ (项目目录的config下)
    2. file:./ (项目目录)
    3. classpath:/config (resources目录的config目录下)
    4. classpath:/ (resources目录)
    • SpringBoot默认给我们配的是最低的优先级, 也就是resources目录下

    3.2 多环境配置

    • 在application.yaml中以---作为分隔, 默认启动8080端口
    • 需要使用哪个端口使用active: 端口名 进行激活即可
    server:
      port: 8080
    spring:
      profiles:
        active: test
    ---
    server:
      port: 8082
    spring:
      profiles: dev
    ---
    server:
      port: 8084
    spring:
      profiles: test
    

    3.3 自动装配原理

    1. SpringBoot启动会加载大量的自动配置类
    2. 我们先看下我们需要的功能有没有在SpringBoot默认写好的自动配置类当中
    3. 再看看这个自动配置类中到底配置了哪些组件; (只要我们要用的组件存在其中, 我们就不需要再手动配置了)
    4. 给容器中自动配置类添加组件的时候, 会从properties类中获取某些属性, 我们只需要在配置文件中指定这些属性的值即可

    xxxAutoConfiguration: 自动配置类, 给容器中添加组件

    xxxProperties: 封装配置文件中相关属性

    • 那么多的自动配置类, 必须在一定的条件下才能生效, 也就是说,我们加载了那么多的配置类, 并不是所有的都生效了
    • 通过启用 debug=true 属性(yaml中是debug: true), 来让控制台打印自动配置报告, 这样我们就可以很方便的只带哪些自动配置类生效
      • Positive matches: 自动配置类启用的: 正匹配
      • Negative matches: (没有启动, 没有匹配成功的自动配置类: 负匹配)
      • Unconditional classes: (没有条件的类)

    四. SpringBoot web开发

    4.1 静态资源导入探究

    • 进入webjars官网,找到jQuery的Maven坐标导入pom.xml
    
        org.webjars
        jquery
        3.6.0
    
    

    http://localhost:8080/webjars/jquery/3.6.0/jquery.js 可以访问到jquery.js

    双击shift,找到WebMvcAutoConfiguration.class

    总结:

    1. 在SpringBoot中, 我们可以使用以下方式处理静态资源
      • webjars localhost:8080/webjars/
      • public, static, /**, resources localhost:8080/
    2. 优先级
      • resources > static(默认) > public

    4.2 首页和图标定制

    • templates目录下的所有页面, 只能通过controller访问
      这个需要模板引擎的支持 thymeleaf, 导入以下依赖
    
        org.springframework.boot
        spring-boot-starter-thymeleaf
    
    
    • 将html页面放在templates目录下
    
    
    
        
        Title
    
    
    
    
    
    

    package com.dz.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import java.util.Arrays;
    
    //在templates目录下的所有页面, 只能通过controller访问
    //这个需要模板引擎的支持 thymeleaf
    @Controller
    public class IndexController {
    
        @RequestMapping("/test")
        public String index(Model model) {
            model.addAttribute("msg","

    hello SpringBoot!

    "); model.addAttribute("users", Arrays.asList("张三","李四")); return "test"; } }

    4.3 SpringMVC配置

    4.3.1 扩展SpringMVC方法一
    package com.dz.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 java.util.Locale;
    
    //如果向diy一些定制化的功能, 只要写这个组件,然后将它交给SpringBoot ,SpringBoot就帮我们自动装配
    //扩展SpringMVC dispatcherServlet
    @Configuration
    public class MyMvcConfig {
    
        //ViewResolver 实现了视图解析器接口的类, 我们就可以把它看做视图解析器
        @Bean
        public ViewResolver myViewResolver() {
            return new MyViewResolver();
        }
    
    
        //自定义了一个自己的视图解析器MyViewResolver
        public static class MyViewResolver implements ViewResolver {
            @Override
            public View resolveViewName(String s, Locale locale) throws Exception {
                return null;
            }
        }
    }
    
    
    4.3.2 扩展SpringMVC方法二[推荐]
    package com.dz.config;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    //如果我们要扩展SpringMVC 官方建议我们这样去做
    @Configuration
    @EnableWebMvc //这个就是导入了一个类DelegatingWebMvcConfiguration, 从容器中获取所有的webmvcconfig
    public class MyMvcConfig implements WebMvcConfigurer {
    
        //视图跳转
    
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/dz").setViewName("test");
        }
    }
    
    

    五. 员工管理系统

    5.1 导入静态资源

    • HTML放在templates目录下
    • 其余放在static目录下

    5.2 首页实现

    package com.dz.config;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    //如果我们要扩展SpringMVC 官方建议我们这样去做
    @Configuration
    public class MyMvcConfig implements WebMvcConfigurer {
    
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/").setViewName("index");
            registry.addViewController("/login.html").setViewName("login");
        }
    }
    
    

    5.3 国际化

    • resources目录下创建 i18n目录, 在 i18n目录 下新建login.properties文件, 再创建login_zh_CN.properties文件(中文), 现在这两个目录被自动整合在Resource Bundle 'login'目录下, 在此目录下再新建login_en_US.properties (英文)

    • 在login.html< html >标签里导入xmlns:th="http://www.thymeleaf.org" , 就可以使用thymeleaf模板了

      • url: @{} , 例如: th:href="@{/css/head.css}"
    • 页面国际化

      • 需要配置 i18n 文件(在application.properties中)

        • #关闭模板引擎的缓存
          spring.thymeleaf.cache=false
          #项目路径设置
          server.servlet.context-path=/dz
          #我们的配置文件放在的真实位置
          spring.messages.basename=i18n.login
          
      • 如果需要项目中进行按钮自动切换, 需要自定义一个组件LocalResolver

      • 记得将自己写的组件配置到Spring容器中 @Bean

    • 从session中取值 [[${session.loginUser}]]

    六. 整合druid, MyBatis, log4j

    6.1 导入依赖

    • pom.xml
    
    
        org.springframework.boot
        spring-boot-starter-web
    
    
    
        mysql
        mysql-connector-java
        runtime
    
    
    
        com.alibaba
        druid-spring-boot-starter
        1.1.10
    
    
    
        org.mybatis.spring.boot
        mybatis-spring-boot-starter
        1.3.2
    
    
    
        log4j
        log4j
        1.2.17
    
    
    
        org.projectlombok
        lombok
    
    

    6.2 编写实体类

    • User.java
    package com.dz.pojo;
    
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    import java.util.Date;
    
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class User {
    
      private int id;
      private String username;
      private String password;
      private int gender;
      private Date registerTime;
    }
    
    

    6.3 编写实体类接口

    • UserMapper.java

      • 如果不使用@mapper注解,则需要在启动类上添加@MapperScan注解, 扫描Mapper接口所在的包

      • @MapperScan(basePackages = "com.dz.mapper")
        
    package com.dz.mapper;
    
    import com.dz.pojo.User;
    import org.apache.ibatis.annotations.Mapper;
    import org.springframework.stereotype.Repository;
    
    import java.util.List;
    
    @Mapper
    @Repository
    public interface UserMapper {
    
        List findAll();
    }
    
    

    6.4 准备Mapper映射文件

    • resources目录下新建mapper目录, 用来存放Mapper映射文件
    • UserMapper.xml
    <?xml version="1.0" encoding="UTF-8"?>
    
    
        
            
            
            
            
            
        
        
    
    

    6.5 添加yaml文件配置信息

    6.5.1 MyBatis配置
    • 扫描映射文件
    • 配置实体类别名
    #MyBatis配置
    mybatis:
      mapper-locations: classpath:mapper/*.xml
      type-aliases-package: com.dz.pojo
      configuration:
        map-underscore-to-camel-case: true
    
    6.5.2 连接数据库配置
    #连接数据库信息
    spring:
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql:///mybatis_db?useUnicode=true&characterEncoding=utf8
        username: root
        password: 8031
        type: com.alibaba.druid.pool.DruidDataSource
    
        #SpringBoot默认是不注入这些属性值的, 需要自己绑定
        #druid数据源专属配置
        #初始化大小, 最大,最小
        initialSize: 5
        minIdle: 5
        maxActive: 20
        #配置获取连接等待超时的时间
        maxWait: 60000
        #配置间隔多久才进行一次检测, 检测需要关闭的空闲连接, 单位是毫秒
        timeBetweenEvictionRunsMillis: 60000
        #配置一个连接在池中最小生存的时间, 单位是毫秒
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT1FROMDUAL
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
    
        #配置监控统计拦截的filters, 去掉后监控界面sql无法统计, 'wall'用于防火墙
        filters: stat,wall,log4j
        #打开PSCache, 并且指定每个连接上PSCache的大小
        maxPoolPreparedStatementPerConnectionSize: 20
        useGlobalDataSourceStat: true
        #通过connectionProperties属性来打开mergeSql功能;慢SQL记录
        connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
    

    6.6 编写log4j配置文件

    • log4j.properties
    # Global logging configuration
    log4j.rootLogger=DEBUG, stdout
    # MyBatis logging configuration
    log4j.logger.org.mybatis.example.BlogMapper=TRACE
    # 配置stdout输出到控制台
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    # 配置stdout设置为自定义布局模式
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    # 配置stdout日志的输出格式  2021-05-01 23:45:26,166  %p日志的优先级 %t线程名  %m日志 %n换行
    log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} - %5p [%t] - %m%n
    

    6.7 编写DruidConfig配置类

    • 使yaml数据源信息生效
    • 后台监控
    • 过滤器
    package com.dz.config;
    
    import com.alibaba.druid.pool.DruidDataSource;
    import com.alibaba.druid.support.http.StatViewServlet;
    import com.alibaba.druid.support.http.WebStatFilter;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.web.servlet.FilterRegistrationBean;
    import org.springframework.boot.web.servlet.ServletRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    import javax.servlet.Filter;
    import javax.sql.DataSource;
    import java.util.HashMap;
    
    @Configuration
    public class DruidConfig {
        @ConfigurationProperties(prefix = "spring.datasource")
        @Bean
        public DataSource druidDatasource(){
            return new DruidDataSource();
        }
    
        //后台监控: 相当于web.xml
        //SpringBoot内置了servlet容器, 所以没有web.xml, 替代方法: ServletRegistrationBean
        @Bean
        public ServletRegistrationBean StatViewServlet(){
            ServletRegistrationBean bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
            //后台需要有人登陆, 账号密码配置
            HashMap initParameters = new HashMap<>();
            //增加配置
            initParameters.put("loginUsername","admin"); //登陆的key 是固定的 loginUsername
            initParameters.put("loginPassword","123456");// loginPassword
            //允许谁可以访问
            initParameters.put("allow","");
            bean.setInitParameters(initParameters);//设置初始化参数
            return bean;
        }
    
        //filter
        @Bean
        public FilterRegistrationBean webStatFilter(){
            FilterRegistrationBean bean = new FilterRegistrationBean<>();
            bean.setFilter(new WebStatFilter());
            //可以过滤哪些请求呢
            HashMap initParameters = new HashMap<>();
            //这些不进行统计
            initParameters.put("exclusions","*.js,*.css,/druid/*");
            bean.setInitParameters(initParameters);
            return bean;
        }
    }
    
    

    七. SpringSecurity

    • 在web开发中, 安全是第一位, 过滤器, 拦截器
    • 注意:thymeleaf-extras-springsecurity4最高支持SpringBoot的版本为2.0.9.RELEASE, 高于2.0.9.RELEASE版本的SpringBoot需要导入thymeleaf-extras-springsecurity5, 我是2.5.0的

    7.1 导入依赖

    
    
        org.springframework.boot
        spring-boot-starter-web
    
    
    
        org.springframework.boot
        spring-boot-starter-thymeleaf
    
    
    
        org.springframework.boot
        spring-boot-starter-security
    
    
    
        org.thymeleaf.extras
        thymeleaf-extras-springsecurity5
        3.0.4.RELEASE
    
    

    7.2 编写SecurityConfig

    • 这里面负责权限认证

    • 开启注解@EnableWebSecurity

    • 继承WebSecurityConfigurerAdapter

    • http为参数的是配置登录等相关参数的,auth为参数的是配置用户和权限的

    package com.dz.config;
    
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    
    //Aop: 拦截器
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        //授权
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            //首页所有人可以访问, 但是功能页只对有相关权限的人开启
            //请求授权的规则
            http.authorizeRequests()
                    .antMatchers("/").permitAll()
                    .antMatchers("/level1/**").hasRole("vip1")
                    .antMatchers("/level2/**").hasRole("vip2")
                    .antMatchers("/level3/**").hasRole("vip3");
    
            //没有权限会跳到登陆页面, 需要开启登陆的页面
            //定制登录页loginPage("/toLogin"), 把登陆的信息提交给我们默认页面Login让其进行判断
            http.formLogin().loginPage("/toLogin")
                    .usernameParameter("user")//实际接收前端参数为user
                    .passwordParameter("pwd")//实际接收前端参数为pwd
                    .loginProcessingUrl("/login");//实际登陆路径
    
            //开启了注销功能, 注销的同时同时删除cookie和session
            http.logout().logoutSuccessUrl("/").deleteCookies().invalidateHttpSession(true);
    
            //防止网站攻击: get post
            http.csrf().disable();//关闭csrf功能,注销失败的原因
            //开启记住我功能 cookie,默认保存两周, 自定义接收前端的参数为remember
            http.rememberMe().rememberMeParameter("remember");
        }
    
        //认证
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            //这些数据正常应该从数据库中读, 现在为了测试是在内存中读取
            auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                    .withUser("dz").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                    .and()
                    .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                    .and()
                    .withUser("visitor").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    
        }
    }
    
    

    7.3 编写Controller

    package com.dz.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class RouterController {
    
        @RequestMapping({"/","/index"})
        public String index(){
            return "index";
        }
    
        @RequestMapping("/toLogin")
        public String toLogin(){
            return "views/login";
        }
    
        @RequestMapping("/level1/{id}")
        public String level1(@PathVariable("id") int id){
            return "views/level1/"+id;
        }
    
        @RequestMapping("/level2/{id}")
        public String level2(@PathVariable("id") int id){
            return "views/level2/"+id;
        }
    
        @RequestMapping("/level3/{id}")
        public String level3(@PathVariable("id") int id){
            return "views/level3/"+id;
        }
    
    }
    
    

    7.4 login.html

    
    
    
        
        
        登录
        
        
    
    
    
    
    

    登录

    记住我
    注册


    blog.kuangstudy.com

    Spring Security Study by 秦疆

    7.5 index.html

    • 注意html的头文件
    • sec:authorize="!isAuthenticated()" 指的是用户没有登陆
    • sec:authorize="hasRole('vip1')" 指的是用户角色是vip1,页面就只显示其角色对应的页面
    
    
    
        
        
        首页
        
        
        
    
    
    
    
    
    
    
    
    
    
    
    
    

    八. Shiro

    8.1 导入依赖

    
    
        org.apache.shiro
        shiro-spring
        1.7.1
    
    

    8.2 编写Realm

    • config/UserRealm.java
    • 自定义的UserRealm 继承AuthorizingRealm
    package com.dz.config;
    
    import com.dz.pojo.User;
    import com.dz.service.UserService;
    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;
    
    //自定义的UserRealm 继承AuthorizingRealm
    public class UserRealm extends AuthorizingRealm {
        @Autowired
        private UserService userService;
    
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
            System.out.println("执行了授权=>doGetAuthorizationInfo");
            return null;
        }
    
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
            System.out.println("执行了认证=>doGetAuthenticationInfo");
    
            UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
    
            //连接真实的数据库
            User user = userService.queryUserByName(userToken.getUsername());
    
            if (user==null){//不存在此用户
                return null;//UnknownAccountException
            }
            //可以加密: MD5 md5盐值加密
            //密码认证, shiro去做, 加密了
            return new SimpleAuthenticationInfo("", user.getPassword(), "");
        }
    }
    
    

    8.3 编写ShiroConfig配置类

    package com.dz.config;
    
    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") DefaultWebSecurityManager defaultWebSecurityManager){
            ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
            //设置安全管理器
            bean.setSecurityManager(defaultWebSecurityManager);
    
            //添加shiro的内置过滤器
            /*
            * anon: 无需认证就可以访问
            * authc: 必须认证后才能访问
            * user: 必须拥有 记住我功能 才能使用
            * perms: 拥有对某个资源的权限才能访问
            * role: 拥有某个角色权限才能访问
            * */
            /*filterMap.put("/user/add","authc");
            filterMap.put("/user/update","authc");*/
            //拦截
            Map filterMap = new LinkedHashMap<>();
            filterMap.put("/user/*","authc");
            bean.setFilterChainDefinitionMap(filterMap);
    
            //设置登陆的请求
            bean.setLoginUrl("/toLogin");
            return bean;
        }
    
        //DefaultWebSecurityManager
        @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();
        }
    }
    
    

    8.4 log4j

    # Global logging configuration
    log4j.rootLogger=DEBUG, stdout
    # MyBatis logging configuration
    log4j.logger.org.mybatis.example.BlogMapper=TRACE
    # 配置stdout输出到控制台
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    # 配置stdout设置为自定义布局模式
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    # 配置stdout日志的输出格式  %d{yyyy-MM-dd HH:mm:ss,SSS}  %p日志的优先级 %t线程名 %c类的全限定名 %m日志 %n换行
    log4j.appender.stdout.layout.ConversionPattern=%d - %5p [%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