springboot
什么是springboot框架?
是一个javaweb框架
好处:
简化开发,约定大于配置
程序=数据结构+算法(集合框架)
程序=面向对象加框架
第一个springboot
HelloController.java
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author pcy
* @date 2021/3/7 - 15:49
*/
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
return "Hello World";
}
}
打包方式如上 java -jar 包名
pom.xml
<dependency>
<!--启动器-->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
banner自动生成网站
https://w
ww.bootschool.net/ascii
将banner放在这里
自动配置原理
pom.xml中
核心依赖:
spring-boot-dependencies
启动器:
<dependency>
<!--启动器-->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
启动器就是springboot的启动场景,比如spring-boot-started,他会帮助我们导入web环境下的所有依赖,springboot会将所以的功能场景都变成一个个启动器,我们要使用什么功能就需要找到对应的启动器started
主程序
//@SpringBootApplication:标注这个类就是一个springboot的应用
@SpringBootApplication
public class HelloWorldApplication {
public static void main(String[] args) {
//将springboot启动
SpringApplication.run(HelloWorldApplication.class, args);
}
}
注解
结论:
springboot所有自动配置都是在启动的时候扫描并加载:spring.factories所以的自动配置都在这里面,但是不一定会生效,要判断条件是否成立,只要导入了对应的start,就会有对应的启动器了,有了启动器,我们自动装配就会生效,然后配置成功
1.springboot在启动时,从类路径下/META-INF/spring.factories获取指定的值
2.将这些自动配置的类导入容器,自动配置就会生效,帮我自动配置
3.以前我们需要自动配置的东西,现在springboot都帮助我们做了
4.整合javaee,解决方案和自动配置的东西都在spring-boot-autoconfigure这个包下
5.他会把所有需要导入的组件,以类名的方式返回,这些组件会被添加到容器当中
6.容器中也会存在非常多的XXXAutoConfiguration的文件,就是这些类给容器中导入这个场景需要的所有的组件,并自动配置,@Configuration,javaConfig!
7.有了自动配置就省去了我们很多工作
启动
SpringApplication
run
yaml
SpringBoot使用一个全局的配置文件 , 配置文件名称是固定的
-
application.properties
语法结构 :key=value
-
application.yml
语法结构 :key:空格 value
application.yml
# 对空格的要求十分重要
server:
port: 8080
# 普通的k-v
name: pcy
# 对象
student:
age: 10
name: pcy
# 行内写法
student1: {name: pcy,age: 3}
# 数组
pets:
-cat
-dag
pet: [cat,dog]
application.properties
# 只能保存键值对
server.port=8080
# 普通的k-v
name=pcy
# 对象
student.age=10
student.name=pcy
给属性赋值的几种方式
注入到我们的配置类中
第一种:yaml可以直接给实体类赋值
@Component
//配置yaml与实体类映射
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private Integer age;
private Boolean happy;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
}
application.yaml
person:
name: pcy
age: 3
happy: false
birth: 2000/01/01
maps: {k1: v1,k2: v2}
lists:
- code
- girl
- music
dog:
name: 旺财
age: 3
person:
name: pcy${random.uuid}
age: ${random.int}
happy: false
birth: 2000/01/01
maps: {k1: v1,k2: v2}
hello: hello11
lists:
- code
- girl
- music
dog:
name: ${person.hello:hello}_旺财
age: 3
HelloWorldApplicationTests.java
@SpringBootTest
class HelloWorldApplicationTests {
@Autowired
private Person person;
@Test
void contextLoads() {
System.out.println(person);
}
}
第二种:properties
pcy.properties
name=pcy
Person.java
@Component
@PropertySource(value = "classpath:pcy.properties")
public class Person {
@Value("${name}")
private String name;
private Integer age;
private Boolean happy;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
}
JSR303校验
JSR303数据校验 , 我们可以在字段是增加一层过滤器验证 , 可以保证数据的合法性
demo
导入依赖
<dependency>
<!--测试-->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Person.java
@Component//注册bean
@ConfigurationProperties(prefix = "person")
@Validated//数据校验
public class Person {
@Email(message = "邮箱格式错误")
private String name;
}
@NotNull(message="名字不能为空")
private String userName;
@Max(value=120,message="年龄最大不能查过120")
private int age;
@Email(message="邮箱格式错误")
private String email;
空检查
@Null 验证对象是否为null
@NotNull 验证对象是否不为null, 无法查检长度为0的字符串
@NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty 检查约束元素是否为NULL或者是EMPTY.
Booelan检查
@AssertTrue 验证 Boolean 对象是否为 true
@AssertFalse 验证 Boolean 对象是否为 false
长度检查
@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内
@Length(min=, max=) string is between min and max included.
日期检查
@Past 验证 Date 和 Calendar 对象是否在当前时间之前
@Future 验证 Date 和 Calendar 对象是否在当前时间之后
@Pattern 验证 String 对象是否符合正则表达式的规则
多环境配置
配置环境的优先级
多环境配置
application.properties
# 默认走的是我们springboot自动生成的文件
# springboot的多环境配置 可选择激活一个环境配置文件
spring.profiles.active=dev
application.yaml
server:
port: 8080
spring:
profiles:
active: dev
---
server:
port: 8081
spring:
profiles: dev
---
server:
port: 8082
spring:
profiles: test
精髓
1、SpringBoot启动会加载大量的自动配置类
2、我们需要的功能有没有在SpringBoot默认写好的自动配置类当中;
3、再看这个自动配置类中到底配置了哪些组件;(只要我们要用的组件存在在其中,我们就不需要再手动配置了)
4、给容器中自动配置类添加组件的时候,会从properties类中获取某些属性。我们只需要在配置文件中指定这些属性的值即可;
**xxxxAutoConfigurartion:自动配置类;**给容器中添加组件
xxxxProperties:封装配置文件中相关属性;
# 可以判断自动配置类是否生效
debug: true
springbootWeb开发
jar:webapp
自动装配
springboot帮助我们配置什么?我们能不能修改?修改哪些东西?能不能拓展?
xxxxAutoConfiguraion向容器中自动配置组件
xxxxProperties:自动配置类,装配配置文件中自定义的一些内容
要解决的问题:
- 导入静态资源
- 首页
- jsp,模版引擎Thymeleaf
- 装配扩展SpringMVC
- 增删改查
- 拦截器
- 国际化
静态资源
什么是webjars?
WebJars are client-side web libraries (e.g. jQuery & Bootstrap) packaged into JAR (Java Archive) files.
四种存放静态资源的路径
总结:在springboot中可以有两种方式处理静态资源
1.webjars http://localhost:8080/webjars/jquery/3.6.0/jquery.js
2.public static resources
首页定制
图标定制
关闭默认图标
# 关闭默认图标
spring.mvc.favicon.enabled=false
thymeleaf模版引擎
Thymeleaf 官网:https://www.thymeleaf.org/
Thymeleaf 在Github 的主页:https://github.com/thymeleaf/thymeleaf
Spring官方文档:找到我们对应的版本
https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/#using-boot-starter
demo
导入依赖:
<!--thymeleaf-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
HelloController.java
@Controller
public class HelloController {
@GetMapping("/hello")
public String test(Model model){
model.addAttribute("msg","<h1>Hello World</h1>");
model.addAttribute("users", Arrays.asList("qin","pcy"));
return "hello";
}
}
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--所以的html元素都可以被Thymeleaf使用-->
<div th:text="${msg}"></div>
<div th:utext="${msg}"></div>
<hr>
<!--<h3 th:each="user:${users}" th:text="${user}"></h3>-->
<h3 th:each="user:${users}">[[${user}]]</h3>
</body>
</html>
结论:只需要使用thymeleaf,只需要导入对应的依赖就行了,我们将html放在templates里面
MVC配置原理
官方文档:https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#boot-features-spring-mvc-auto-configuration
MyMvcConfig.java
public class MyMvcConfig {
// 想要定义一些功能只要写这个组件,然后交给springboot,就会帮助我们自动装配
// 扩展springmvc dispatcherservlet
@Bean
public MyViewResolver myViewResolver(){
return new MyViewResolver();
}
public static class MyViewResolver implements ViewResolver{
@Override
public View resolveViewName(String s, Locale locale) throws Exception {
return null;
}
}
}
扩展springmvc
//如果我们要扩展springmvc,官方建议我们这样去做
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/hello1").setViewName("hello");
}
}
Configuration:给我们扩展了springmvc的东西
如何写一个网站
1.有一个熟悉的后台模版,x-admin
2.前端界面。至少自己能够通过前端框架,组合出来一个网站页面
3,让这个网站能够独立运行
整合JDBC
对于数据访问层,无论是 SQL(关系型数据库) 还是 NOSQL(非关系型数据库),Spring Boot 底层都是采用 Spring Data 的方式进行统一处理。
Spring Boot 底层都是采用 Spring Data 的方式进行统一处理各种数据库,Spring Data 也是 Spring 中与 Spring Boot、Spring Cloud 等齐名的知名项目。
Sping Data 官网:https://spring.io/projects/spring-data
数据库相关的启动器 :可以参考官方文档:
https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#using-boot-starter
jdbc的模版
JdbcTemplate
1、有了数据源(com.zaxxer.hikari.HikariDataSource),然后可以拿到数据库连接(java.sql.Connection),有了连接,就可以使用原生的 JDBC 语句来操作数据库;
2、即使不使用第三方第数据库操作框架,如 MyBatis等,Spring 本身也对原生的JDBC 做了轻量级的封装,即JdbcTemplate。
3、数据库操作的所有 CRUD 方法都在 JdbcTemplate 中。
4、Spring Boot 不仅提供了默认的数据源,同时默认已经配置好了 JdbcTemplate 放在了容器中,程序员只需自己注入即可使用
5、JdbcTemplate 的自动配置是依赖 org.springframework.boot.autoconfigure.jdbc 包下的 JdbcTemplateConfiguration 类
第一个实例
package com.kuang.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
* @author pcy
* @date 2021/3/10 - 17:21
*/
@RestController
public class JDBCController {
@Autowired
JdbcTemplate jdbcTemplate;
@GetMapping("/list")
public List<Map<String,Object>> selectCount(){
String sql="select * from account";
List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
return maps;
}
@GetMapping("add")
public String addUser(){
String sql="insert into account(id,name,money) values(6,'pcy','2000')";
int update = jdbcTemplate.update(sql);
return "OK";
}
@GetMapping("update/{id}")
public String updateUser(@PathVariable("id") int id){
String sql="update account set name=?,money=? where id="+id;
Object[] object=new Object[2];
object[0]="pcy1";
object[1]=10000;
int update = jdbcTemplate.update(sql,object);
return "OK";
}
@GetMapping("delete/{id}")
public String deleteUser(@PathVariable("id") int id){
String sql="delete from account where id=?";
int update = jdbcTemplate.update(sql,id);
return "OK";
}
}
application.yaml
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mall?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
注意:
这里的username千万不能写成data-username,password同理
整合Druid数据源
Druid 是阿里巴巴开源平台上一个数据库连接池实现,结合了 C3P0、DBCP 等 DB 池的优点,同时加入了日志监控。
Druid 可以很好的监控 DB 池连接和 SQL 的执行情况,天生就是针对监控而生的 DB 连接池。
Druid已经在阿里巴巴部署了超过600个应用,经过一年多生产环境大规模部署的严苛考验。
Spring Boot 2.0 以上默认使用 Hikari 数据源, Hikari 与 Driud 都是当前 Java Web 上最优秀的数据源
第一个实例:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
application.yaml
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mall?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.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
config包下的DruidConfig.java
package com.kuang.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.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @author pcy
* @date 2021/3/10 - 18:23
*/
@Configuration
public class DruidConfig {
/*
将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建
绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效
@ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中
前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
*/
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
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;
}
//配置 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;
}
}
运行之后登陆http://localhost:8080/druid出现以下页面
Mybatis整合
整合包
导入依赖
<!--不是官方的-->
<!-- 引入 myBatis,这是 MyBatis官方提供的适配 Spring Boot 的,而不是Spring Boot自己的-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
application.yaml
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mall?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
测试是否连接成功?
Springboot05MybatisApplicationTests.java
package com.kuang;
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.SQLException;
@SpringBootTest
class Springboot05MybatisApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
System.out.println(dataSource.getClass());
System.out.println(dataSource.getConnection());
}
}
第一个整合实例
application.yaml
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mall?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
#指定myBatis的核心配置文件与Mapper映射文件
mybatis:
mapper-locations: classpath:mybatis/mapper/*.xml
# 注意:对应实体类的路径
type-aliases-package: com.kuang.pojo
User.java
package com.kuang.pojo;
/**
* @author pcy
* @date 2021/3/10 - 20:10
*/
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
UserMapper.java
package com.kuang.mybatis.mapper;
import com.kuang.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @author pcy
* @date 2021/3/10 - 20:10
*/
@Mapper
@Repository
public interface UserMapper {
//选择全部用户
List<User> selectUser();
//根据id选择用户
User selectUserById(int id);
//添加一个用户
int addUser(User user);
//修改一个用户
int updateUser(User user);
//根据id删除用户
int deleteUser(int id);
}
UserController.java
package com.kuang.controller;
import com.kuang.mybatis.mapper.UserMapper;
import com.kuang.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @author pcy
* @date 2021/3/10 - 20:50
*/
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
//选择全部用户
@GetMapping("/selectUser")
public String selectUser(){
List<User> users = userMapper.selectUser();
for (User user : users) {
System.out.println(user);
}
return "ok";
}
//根据id选择用户
@GetMapping("/selectUserById")
public String selectUserById(){
User user = userMapper.selectUserById(1);
System.out.println(user);
return "ok";
}
//添加一个用户
@GetMapping("/addUser")
public String addUser(){
userMapper.addUser(new User(5,"阿毛","456789"));
return "ok";
}
//修改一个用户
@GetMapping("/updateUser")
public String updateUser(){
userMapper.updateUser(new User(5,"阿毛","421319"));
return "ok";
}
//根据id删除用户
@GetMapping("/deleteUser")
public String deleteUser(){
userMapper.deleteUser(5);
return "ok";
}
}
UserMapper1.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.kuang.mybatis.mapper.UserMapper">
<select id="selectUser" resultType="User">
select * from user
</select>
<select id="selectUserById" resultType="User">
select * from user where id = #{id}
</select>
<insert id="addUser" parameterType="User">
insert into user (id,name,pwd) values (#{id},#{name},#{pwd})
</insert>
<update id="updateUser" parameterType="User">
update user set name=#{name},pwd=#{pwd} where id = #{id}
</update>
<delete id="deleteUser" parameterType="int">
delete from user where id = #{id}
</delete>
</mapper>
SpringSecurity(安全)
做网站的时候应该在设计之初就考虑安全问题
漏洞,隐私
shiro,springsecurity:认证和授权
- 功能权限
- 访问权限
- 菜单权限
- 拦截器,过滤器
导入依赖:
<!--thymeleaf-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
- WebSecurityConfigurerAdapter:自定义Security策略
- AuthenticationManagerBuilder:自定义认证策略
- @EnableWebSecurity:开启WebSecurity模式
Spring Security的两个主要目标是 “认证” 和 “授权”(访问控制)。
package com.kuang.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;
/**
* @author pcy
* @date 2021/3/11 - 8:42
*/
@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");
//没有权限会进入登录页面
http.formLogin();
//注销,开启注销功能,注销后跳到登录页面
http.csrf().disable();//关闭csrf功能,登陆失败原因
http.logout().logoutSuccessUrl("/");
//
}
//认证 springboot在2.1.x可以正常使用
//密码编码:passwordEncoder
//在spring Security5.0+新增了很多加密方法
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//这些数据正常从数据库中读取
//BCryptPasswordEncoder可以通过MD5加密等
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("kuang").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
.and().withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and().withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
}