10_SpringBoot更加详细
一. 原理初探
1.1 自动装配
1.1.1 pom.xml
- spring-boot-dependencies: 核心依赖在父工程中
- 我们在写入或者引入一些SpringBoot依赖的时候, 不需要指定版本, 就是因为有这些版本仓库
1.1.2 启动器
- <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter</artifactId>
 </dependency>
 
- 启动器: 说白了就是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
 
 
- application.properties
配置文件的作用: 修改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<String, Object> map;
 private List<Object> 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一个依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
补充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中
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
类上方使用注解@Validated 开启数据校验
@Component
@ConfigurationProperties(prefix = "person")
@Validated //数据校验
public class Person {
    @Email(message = "邮箱格式错误!")
    private String name;
    //省略...
}
补充5: 热加载
- 导入依赖
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-devtools</artifactId>
	<optional>true</optional>
</dependency>
- 修改IDEA设置 Settings > Build,Execution > Compiler > 勾选Build project automatically
- 之后项目修改后,只需Build一下即可,无需重新部署项目
2.2.4 结论
- 配置yaml和配置properties都可以获取到值, 强烈推荐yaml
- 如果我们在某个业务中, 只需要获取配置文件中的某个值, 可以使用一下@Value
- 但如果我们专门编写了一个JavaBean来和配置文件进行映射, 就直接使用@ConfigurationProperties, 不要犹豫
三. 配置文件优先级和多环境配置
3.1 application.yaml生效优先级
- file:./config/ (项目目录的config下)
- file:./ (项目目录)
- classpath:/config (resources目录的config目录下)
- 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 自动装配原理
- SpringBoot启动会加载大量的自动配置类
- 我们先看下我们需要的功能有没有在SpringBoot默认写好的自动配置类当中
- 再看看这个自动配置类中到底配置了哪些组件; (只要我们要用的组件存在其中, 我们就不需要再手动配置了)
- 给容器中自动配置类添加组件的时候, 会从properties类中获取某些属性, 我们只需要在配置文件中指定这些属性的值即可
xxxAutoConfiguration: 自动配置类, 给容器中添加组件
xxxProperties: 封装配置文件中相关属性
- 那么多的自动配置类, 必须在一定的条件下才能生效, 也就是说,我们加载了那么多的配置类, 并不是所有的都生效了 
- 通过启用 debug=true 属性( - yaml中是debug: true - ), 来让控制台打印自动配置报告, 这样我们就可以很方便的只带哪些自动配置类生效 - Positive matches: 自动配置类启用的: 正匹配
- Negative matches: (没有启动, 没有匹配成功的自动配置类: 负匹配)
- Unconditional classes: (没有条件的类)
 
四. SpringBoot web开发
4.1 静态资源导入探究
- 进入webjars官网,找到jQuery的Maven坐标导入pom.xml
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.6.0</version>
</dependency>
http://localhost:8080/webjars/jquery/3.6.0/jquery.js 可以访问到jquery.js
双击shift,找到WebMvcAutoConfiguration.class
总结:
- 在SpringBoot中, 我们可以使用以下方式处理静态资源
- webjars localhost:8080/webjars/
- public, static, /**, resources localhost:8080/
 
- 优先级
- resources > static(默认) > public
 
4.2 首页和图标定制
- 在templates目录下的所有页面, 只能通过controller访问
 这个需要模板引擎的支持 thymeleaf, 导入以下依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- 将html页面放在templates目录下
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--所有的html元素都可以被 thymeleaf替换接管: th: 元素名-->
<!--转义,非转义-->
<!--<h1>hello SpringBoot!</h1>-->
<div th:text="${msg}"></div>
<!--hello SpringBoot!-->
<div th:utext="${msg}"></div>
<hr>
<!--遍历集合-->
<h3 th:each="user:${users}" th:text="${user}"></h3>
</body>
</html>
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","<h1>hello SpringBoot!</h1>");
        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
<!--web-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mysql-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<!--druid-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>
<!--mybatis-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>
<!--log4j-->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
<!--lombok-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
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<User> findAll();
}
6.4 准备Mapper映射文件
- resources目录下新建mapper目录, 用来存放Mapper映射文件
- UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dz.mapper.UserMapper">
    <resultMap id="user_resultMap" type="User">
        <id column="id" property="id"/>
        <result column="username" property="username"/>
        <result column="password" property="password"/>
        <result column="gender" property="gender"/>
        <result column="register_time" property="registerTime"/>
    </resultMap>
    <select id="findAll" resultMap="user_resultMap">
        select id,username,password,gender,register_time
        from t_user
    </select>
</mapper>
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<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        //后台需要有人登陆, 账号密码配置
        HashMap<String, String> 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<Filter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new WebStatFilter());
        //可以过滤哪些请求呢
        HashMap<String, String> 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 导入依赖
<!--web-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--thymeleaf-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--security-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!--thymeleaf-security整合包-->
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>
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
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>登录</title>
    <!--semantic-ui-->
    <link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
</head>
<body>
<!--主容器-->
<div class="ui container">
    <div class="ui segment">
        <div style="text-align: center">
            <h1 class="header">登录</h1>
        </div>
        <div class="ui placeholder segment">
            <div class="ui column very relaxed stackable grid">
                <div class="column">
                    <div class="ui form">
                        <form th:action="@{/login}" method="post">
                            <div class="field">
                                <label>Username</label>
                                <div class="ui left icon input">
                                    <input type="text" placeholder="Username" name="user">
                                    <i class="user icon"></i>
                                </div>
                            </div>
                            <div class="field">
                                <label>Password</label>
                                <div class="ui left icon input">
                                    <input type="password" name="pwd">
                                    <i class="lock icon"></i>
                                </div>
                            </div>
                            <div class="field">
                                <input type="checkbox" name="remember"> 记住我
                            </div>
                            <input type="submit" class="ui blue submit button"/>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <div style="text-align: center">
            <div class="ui label">
                </i>注册
            </div>
            <br><br>
            <small>blog.kuangstudy.com</small>
        </div>
        <div class="ui segment" style="text-align: center">
            <h3>Spring Security Study by 秦疆</h3>
        </div>
    </div>
</div>
<script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}"></script>
<script th:src="@{/qinjiang/js/semantic.min.js}"></script>
</body>
</html>
7.5 index.html
- 注意html的头文件
- sec:authorize="!isAuthenticated()" 指的是用户没有登陆
- sec:authorize="hasRole('vip1')" 指的是用户角色是vip1,页面就只显示其角色对应的页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>首页</title>
    <!--semantic-ui-->
    <link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
    <link th:href="@{/qinjiang/css/qinstyle.css}" rel="stylesheet">
</head>
<body>
<!--主容器-->
<div class="ui container">
    <div class="ui segment" id="index-header-nav" th:fragment="nav-menu">
        <div class="ui secondary menu">
            <a class="item"  th:href="@{/index}">首页</a>
            <!--登录注销-->
            <div class="right menu">
                <!--如果未登录: 显示登陆按钮-->
                <div sec:authorize="!isAuthenticated()">
                    <a class="item" th:href="@{/toLogin}">
                        <i class="sign-in icon"></i> 登录
                    </a>
                </div>
                <!--如果已登陆:显示用户名+注销按钮-->
                <div sec:authorize="isAuthenticated()">
                    <a class="item">
                        用户名: <span sec:authentication="name"></span>
                        <!--角色: <span sec:authentication="principal.getAuthorities()"></span>-->
                    </a>
                </div>
                <div sec:authorize="isAuthenticated()">
                    <a class="item" th:href="@{/logout}">
                        <i class="sign-out icon"></i> 注销
                    </a>
                </div>
            </div>
        </div>
    </div>
    <div class="ui segment" style="text-align: center">
        <h3>Spring Security Study by 秦疆</h3>
    </div>
    <div>
        <br>
        <div class="ui three column stackable grid">
            <!--菜单根据用户的角色动态的实现-->
            <div class="column" sec:authorize="hasRole('vip1')">
                <div class="ui raised segment">
                    <div class="ui">
                        <div class="content">
                            <h5 class="content">Level 1</h5>
                            <hr>
                            <div><a th:href="@{/level1/1}"><i class="bullhorn icon"></i> Level-1-1</a></div>
                            <div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div>
                            <div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="column" sec:authorize="hasRole('vip2')">
                <div class="ui raised segment">
                    <div class="ui">
                        <div class="content">
                            <h5 class="content">Level 2</h5>
                            <hr>
                            <div><a th:href="@{/level2/1}"><i class="bullhorn icon"></i> Level-2-1</a></div>
                            <div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i> Level-2-2</a></div>
                            <div><a th:href="@{/level2/3}"><i class="bullhorn icon"></i> Level-2-3</a></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="column" sec:authorize="hasRole('vip3')">
                <div class="ui raised segment">
                    <div class="ui">
                        <div class="content">
                            <h5 class="content">Level 3</h5>
                            <hr>
                            <div><a th:href="@{/level3/1}"><i class="bullhorn icon"></i> Level-3-1</a></div>
                            <div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div>
                            <div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}"></script>
<script th:src="@{/qinjiang/js/semantic.min.js}"></script>
</body>
</html>
八. Shiro
8.1 导入依赖
<!--shiro-spring-->
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.7.1</version>
</dependency>
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<String, String> 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
10_SpringBoot更加详细的更多相关文章
- ZIP压缩算法详细分析及解压实例解释
		最近自己实现了一个ZIP压缩数据的解压程序,觉得有必要把ZIP压缩格式进行一下详细总结,数据压缩是一门通信原理和计算机科学都会涉及到的学科,在通信原理中,一般称为信源编码,在计算机科学里,一般称为数据 ... 
- SASS教程sass超详细教程
		SASS安装及使用(sass教程.详细教程) 采用SASS开发CSS,可以提高开发效率. SASS建立在Ruby的基础之上,所以得先安装Ruby. Ruby的安装: 安装 rubyinstaller- ... 
- 史上最详细git教程
		题外话 虽然这个标题很惊悚,不过还是把你骗进来了,哈哈-各位看官不要着急,耐心往下看 Git是什么 Git是目前世界上最先进的分布式版本控制系统. SVN与Git的最主要的区别 SVN是集中式版本控制 ... 
- gulp详细入门教程
		本文链接:http://www.ydcss.com/archives/18 gulp详细入门教程 简介: gulp是前端开发过程中对代码进行构建的工具,是自动化项目的构建利器:她不仅能对网站资源进行优 ... 
- windows环境下sublime的nodejs插件详细安装图解
		前面的话 搜索了好多文档后,才成功地安装了sublime text3的nodejs插件.为了存档,也为了方便有同样需求的朋友,将其安装过程详细记录如下 安装nodejs 虽然nodejs官网提供了 ... 
- 【详细教程】论android studio中如何申请百度地图新版Key中SHA1值
		一.写在前面 现在越来越多的API接口要求都要求提供我们的项目SHA1值,开发版目前还要求不高,但是发布版是必定要求的.而目前定位在各大APP中也较为常见,当下主流的百度地图和高德地图都在申请的时候会 ... 
- Oracle 11g必须开启的服务及服务详细介绍
		转自:http://www.educity.cn/shujuku/404120.html 成功安装Oracle 11g数据库后,你会发现自己电脑运行速度会变慢,配置较低的电脑甚至出现非常卡的状况,通 ... 
- python select网络编程详细介绍
		刚看了反应堆模式的原理,特意复习了socket编程,本文主要介绍python的基本socket使用和select使用,主要用于了解socket通信过程 一.socket模块 socket - Low- ... 
- Linux1  在Linux(CentOS)上安装MySql详细记录
		前记: 毕业两年了,前两天换了份工作,由以前的传统行业跳到了互联网行业.之前的公司一直在用WinServer2003+Tomcat+SqlServer/Oracle这套部署环境.对于Linux+To ... 
随机推荐
- 【前端面试】Vue面试题总结(持续更新中)
			Vue面试题总结(持续更新中) 题目参考链接 https://blog.csdn.net/weixin_45257157/article/details/106215158 由于已经有很多前辈深造VU ... 
- 跟我读论文丨Multi-Model Text Recognition Network
			摘要:语言模型往往被用于文字识别的后处理阶段,本文将语言模型的先验信息和文字的视觉特征进行交互和增强,从而进一步提升文字识别的性能. 本文分享自华为云社区<Multi-Model Text Re ... 
- 水电表/压力表/传感器/流量计/行车记录仪/分贝仪等 超低功耗LCD段码液晶驱动IC-VKL076(VKL系列)SSOP28  19*4COM,工作电流约7.5微安
			产品品牌:永嘉微电/VINKA 产品型号:VKL076 封装形式:SSOP28 产品年份:新年份 概述: VKL076 SSOP28是一个点阵式存储映射的LCD驱动器,可支持最大76点(19SEGx4 ... 
- firewall 命令简单操作
			Firewalld 是维护防火墙策略的守护程序的名称.使用 firewall-cmd 命令与防火墙配置进行交互, 使用区域概念对与系统交互的流量进行分段.网络接口分配给一个或多个区域,每个区域都包含允 ... 
- 操作表查询&操作表创建&操作表删除&操作表修改
			2.操作表 C(create):创建 语法: create table 表明( 列名1 数据类型1, 列名2 数据烈性2, .... 列名n 数据类型n ); create table Student ... 
- 重写Object的equals方法和Objects的equals方法
			Object类的equals方法默认比较的是两个对象的地址值,没有意义 所以我们需要重写equals方法,比较两个对象的属性值(name,age等等): 对象的属性值一样返回true否则返回false ... 
- 你的工具包已到货「GitHub 热点速览 v.22.31」
			如果你经常用 shell 记得看看本周特推里的 gum,它能给你的 shell 增加新趣味.除了这个 shell kit,我们还有 dashboard kit--tabler,功能技能 kit eng ... 
- 利用基于Python的Pelican打造一个自己的个人纯静态网站
			原文转载自「刘悦的技术博客」https://v3u.cn/a_id_100 其实呢这么多年以来我一直建议每个有技术追求的开发者都要有写技术博客记笔记的良好习惯,一来可以积累知识,二来可以帮助别人,三来 ... 
- OpenSSF的开源软件风险评估工具:Scorecards
			对于IT从业者来说,Marc Andreessen 十年前提出"软件吞噬世界"的观点早已耳熟能详.无论是私人生活还是公共领域,软件为现代社会的方方面面提供动力,对现代经济和国家安全 ... 
- DTSE Tech Talk丨第3期:解密数据隔离方案,让SaaS应用开发更轻松
			摘要:解读云上前沿技术,畅聊开发应用实践.专家团队授课,答疑解惑,助力开发者使用华为云开放能力进行应用构建.技术创新. 围绕当下许多企业青睐的SaaS应用开发,华为云DTSE技术布道师李良龙为大家带来 ... 
