文章目录
SpringBoot
Spring是如何简化Java开发的
主要采用了四种关键策略
基于降低POJO轻量级和最小侵入性编程
通过IOC,依赖注入(DI)和面向接口实现松耦合
基于切面(AOP)和惯例进行声明式编程
通过切面和模板减少样式代码
一、🎃什么是SpringBoot
- 一个javaweb的开发框架
- 简化开发,
约定大于配置
🤔
优点
- 为所有Srping开发者更快的入门
开箱即用
,提供各种默认配置起来简化项目配置- 内嵌式容器简化web项目
- 没有冗余代码生成和XML配置的要求
这里的这句话我觉的很好,算法还是重要的🤔
程序=数据结构+算法:程序员
程序=面向对象+框架:码农
使用Spring Boot到底有多爽,
这里配上狂神老师的一个图
🤣🤣🤣🤣
二、🎃什么是微服务架构
1、单体应用架构
- 所谓单体应用架构 (all in one) 是指,我们将一个应用的的所有应用服务都封装在一个应用中
- 无论是ERP、CRM或是其他什么系统,你都把数据库访问,web访问,等等各个功能放到一个war包内。
- 这样做的好处是,易于开发和测试,也十分方便部署;当需要扩展时,只需要将war复制多份,然后放到多个服务器上,再做个负载均衡就可以了。
- 单体应用架构的
缺点
是,哪怕我要修改一个非常小的地方,我都需要停掉整个服务
,重新打包、部署这个应用war包。特别是对于一个大型应用,我们不可能吧所有内容都放在一个应用里面,我们如何维护、如何分工合作都是问题。
2、微服务架构
所谓微服务架构,就是打破之前all in one的架构方式,把每个功能元素独立
出来。把独立出来的功能元素的动态组合
,需要的功能元素才去拿来组合,需要多一些时可以整合多个功能元素。所以微服务架构是对功能元素进行复制
,而没有对整个应用进行复制
。
这样做的好处是:
节省了调用资源。
每个功能元素的服务都是一个可替换的、可独立升级的软件代码
3、如何构建微服务
一个大型系统的微服务架构,就像一个复杂交织的神经网络
,每一个神经元就是一个功能元素,它们各自完成自己的功能,然后通过http相互请求调用。比如一个电商系统,查缓存、连数据库、浏览页面、结账、支付等服务都是一个个独立的功能服务,都被微化了,它们作为一个个微服务共同构建了一个庞大的系统。如果修改其中的一个功能,只需要更新升级其中一个功能服务单元即可。
但是这种庞大的系统架构给部署和运维带来很大的难度。于是,spring为我们带来了构建大型分布式微服务的全套、全程产品:
三、🎃第一个SpringBoot程序
多种方式可以建立SpringBoot项目
反正我的理念就是那种简单用那个,哪个好用用哪个,我用idea集成
三种方式快速搭建springboot项目
学到的小技巧:
- Jrebel热部署工具,我在网上看到这个的评价比较高,比那个自带的devtools好,
我是最后将版本降低才成功的
教程地址:https://blog.csdn.net/qq_42319677/article/details/112979915
- 更改项目的端口号
在application.properties中写
server.port=8081
这里提到了,就是用properties或者yaml配置文件都可以
,这里还没有讲到这个文件所以先不管了,遇到了再说
- 🧨Banner
这个特别好玩,啊哈啊啊
,在线生成网址
这个就是把你复制的那个样式放在resources的banner.txt
下,然后重启一下就会看到了
四、🎃原理初探
1、Springboot自动装配原理
🎆pom.xml
- 🎈Spring-boot-dependencies:
核心依赖
在父工程
中
可以去看看那个父工程里面有好多好多的依赖包
- 🎈我们在写或者引入一些Springboot依赖的时候,不需要指定版本,就是因为有这个版本仓库
🎆启动器
- 🎈那好多的starter就是启动器,是根据功能场景划分的
🎆主程序
- springboot在启动的时候,从类路径下/META-INF/spring.factories 获取指定的值
- 将这些自动配置的类导入容器,自动配置就会生效,帮我进行自动配置!
- 以前我们需要自动配置的东西,现在springboot帮我们做了!
- 整合javaEE,解决方案和自动配置的东西都在 spring-boot-autoconfigure-2.2.0.RELEASE.jar 这个包下
- 它会把所有需要导入的组件,以类名的方式返回,这些组件就会被添加到容器
- 容器中也会存在非常多的xxxAutoConfiguration的文件(@Bean),就是这些类给容器中导入了这个场景需要的所有组件;并自动配置, @Configuration ,avaConfig!
- 有了自动配置类,免去了我们手动编写配置文件的工作!
对于springboot提供的其他模块配置的装配,其通过文件
META-INF/spring.factories
来加载,starter关于配置的自动装配,即从此处入手
🙃 源码我就不分析了,水平到的时候,我再回来,这里看到别人的思维导图,https://www.processon.com/view/608bb5e86376894f999fb008?fromnew=1
2、主启动类怎么运行
🎆SpringApplication
主要做了以下四件事
- 推断应用的类型是普通的项目还是Web项目
- 查找并加载所有可用初始化器,设置到initializers属性中
- 找出所有的应用程序监听器,设置到listeners属性中
- 推断并设置main万法的定义类,找到运行的主类
🎆Run
五、🎃SpringBoot配置
1、yaml配置
- YAML是"YAML Ain’t a Markup Language” (YAML不是一种置标语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是:"Yet Another Markup Language”(仍是一种置标语言)
- YAML A Markup Language : 是一个标记语言
- YAML isnot Markup Language : 不是一个标记语言
🎆标记语言
- 🎈yaml配置:
server:
port: 8080
- 🎈xml配置:
<server>
<port>8081</port>
</server>
- 🎈xml基本语法:
2、属性赋值
🎆例子
Dog:
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class Dog {
private String name;
private Integer age;
}
Person:
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
@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<Dog> lists;
private Dog dog;
}
yaml文件
person:
name: lzy
age: 3
happy: false
birth: 2019/11/02
maps: {k1: v1, k2:v2}
list:
- code
- music
- girl
dog:
name: 旺财
age: 3
测试类
@SpringBootTest
class Springboot02ConfigApplicationTests {
@Autowired
private Person person;
@Test
void contextLoads() {
System.out.println(person);
}
}
官方解释:通过使用spring-boot配置处理器jar,您可以轻松地从@ConfigurationProperties注释的项目生成自己的配置元数据文件。jar包含一个Java注释处理器,在编译项目时调用它。
🎆yaml文件:
🎆Controller
💥总结:
可以通过yaml配置文件和@ConfigurationProperties(prefix = "person")注解配合的方式完成对属性的赋值,这种可以代替原生的(没有yaml文件),在每一个属性头上加@Value的方式
当有yaml文件的时候,要通过yaml文件给属性赋值的话,可以使用@ConfigurationProperties或者使用@Value来去给属性赋值
松散绑定:比如yaml中写的last-name,这个和lastName是一样的,-后面跟着的字母默认是大写的。这就是松散绑定(自我感觉和数据可的驼峰命名法很像)
如果骂我们在某个业务中,只需要获取配置文件中的某个值,可以使用一下@value,如果说我们专门编写了一个JavaBean来和JavaBean来和配置文件进行映射,就直接使用@ConfigurationProperties
3、JSR303校验
在一个pojo实体类上,写上了注解@Validated
的话就可以开启数据校验了,然后在你想要校验的属性上加上不同类型的数据校验的注解(例如@Email
),这样的话如果当你给这个加了校验注解的属性不是赋邮箱类型的值的话,就会报错,总之使用了这个数据校验的话,可以保证数据的正确性
4、多环境配置以及配置环境文件
通过多环境的配置,可以适用于不同的开发环境
六、🎃SpringBoot Web开发
🎆springboot 到底帮我们配置了什么? 我们能不能进行修改?能修改哪些东西? 能不能扩展?
- xxxxAutoConfiguraion… 向容器中自动配置组件
- xxxxProperties:自动配置类,装配配置文件中自定义的一些内容!
🎆要解决的问题:
- 导入静态资源…
- 首页
- jsp,模板引擎Thymeleaf
- 装配扩展SpringMVC
- 增删改查
- 拦截器
- 国际化!
1、静态资源导入
🎆通过webjars引入
localhost:8080/webjars
就是引入那些maven那些坐标的
🎆通过一些特定的位置
🎆自定义静态资源访问路径
这里就是说如果你自定义了静态资源的访问路径的话,那么springboot为你提供的默认的资源访问路径都会失效
2、首页
也就是当你访问localhost:8080/的时候默认的首页,会从静态资源目录里面找名称为index的页面,还是遵循那个优先级
3、thymeleaf模板引擎
我感觉这东西就和一个前端一样,这样的取值的方法
🎆Thymeleaf语法
参考官方文档https://www.docs4dev.com/docs/zh/thymeleaf/3.0/reference/using_thymeleaf.html#using-texts
4、装配扩展SprinngMVC
💥
这里只是展示了一下视图解释器,但是里面还能配置好多的东西,也就是是说在springboot帮你做了好多事情的基础上,你还可以去扩展你自己需要的东西,嗯!很棒
这里参考一个大佬的文章https://blog.csdn.net/zhangpower1993/article/details/89016503
🎃七、员工管理系统
1、国际化
2、拦截器
🎆配置拦截器
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 登录之后,应该有用户的session;
Object loginUser = request.getSession().getAttribute("loginUser");
if(loginUser == null){
request.setAttribute("msg", "没有权限,请先登录");
request.getRequestDispatcher("/index").forward(request, response);
return false;
}else{
return true;
}
}
}
这里判断一下你设置的是否登录过的依据,然后进行放行或者不放行
🎆然后注册一下
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").
excludePathPatterns("/index", "/user/login", "/", "/css/**", "/js/**", "/img/**");
}
注意这里你应该放行的路径
其他的我就看了看,就不做笔记了
🎃八、数据库相关
1、整合JDBC
🎆导入坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.31</version>
</dependency>
🎆配置yml文件
spring:
datasource:
username: root
password: xxxx
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
默认加载的数据源是这个,然后可以通过springboot自带的jdbcTemplate中即可直接使用,但是一般开发中很少使用这个,所以我还是当做了解就行了
2、整合Druid
- Druid 是阿里巴巴开源平台上一个数据库连接池实现,结合了 C3PO、DBCP、PROXOOL等 DB 池的优点,同时加入了日志监控。
- Druid 可以很好的监控 DB 池连接和 SQL 的执行情况,天生就是针对监控而生的 DB 连接池
- Spring Boot 2.0 以上默认使用 Hikari 数据源,可以说 Hikari 与 Driud 都是当前 Java Web 上最优秀的数据源,我们来重点介绍 Spring Boot 如何集成 Druid 数据源,如何实现数据库监控。
🎆导入坐标
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.15</version>
</dependency>
🎆yaml配置
spring:
datasource:
username: root
password: lige0612
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
#则导入 Log4i 依赖即可,Maven 址: https://mvnrepository.com/artifact/Log4j/log4j
filters: stat,wal1,1og4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSglMillis=500
和整合jdbc的就差一个type,其他的用到的再说
这里发现一个之前没见过的Druid的后台监控,记录一下
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybaits?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
username: root
password: lige0612
type: com.alibaba.druid.pool.DruidDataSource
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,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DruidDataSource druidDataSource(){
return new DruidDataSource();
}
// 后台监控
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
// ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
// 后台需要有人登录,账号密码配置
Map<String, String> initParameters = new HashMap<>();
initParameters.put("loginUsername", "admin"); // 都是固定的
initParameters.put("loginPassword", "123456");
//允许谁可以访问
initParameters.put("allow", "");
bean.setInitParameters(initParameters);
return bean;
}
}
3、整合mybaits
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.31</version>
</dependency>
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
username: root
password: lige0612
mybatis:
type-aliases-package: com.lzy.pojo
mapper-locations: classpath:mapper/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String name;
private String pwd;
}
@Mapper
@Repository
public interface UserMapper{
List<User> queryList();
}
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/list")
public List<User> list(){
return userMapper.queryList();
}
}
4、整合mybatis-plus
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
spring:
datasource:
password: lige0612
username: root
url: jdbc:mysql://localhost:3306/mybatis?characterEncoding=UTF-8&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
configuration:
#在映射实体或者属性时,将数据库中表名和字段名中的下划线去掉,按照驼峰命名法映射
map-underscore-to-camel-case: true
#控制台打印完整带参数SQL语句
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
id-type: ASSIGN_ID
type-aliases-package: com.lzy.pojo
@Data
public class User {
private Integer id;
private String name;
private String pwd;
}
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/user")
public List<User> user(){
List<User> list = userService.list();
return list;
}
}
做个笔记,等的看
🎃九、SpringSecurity
1、环境搭建
这里遇到一个问题就是配置了thyealeaf不跳转到templates中,通过坐标的版本解决
2、用户认证和授权
-
Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入 spring-boot-starter-security 模块,进行少量的配置,即可实现强大的安全管理!
-
记住几个类:
- WebSecurityConfigurerAdapter: 自定义Security策略
- AuthenticationManagerBuilder: 自定义认证策略
- @EnableWebSecurity: 开启WebSecurity模式
-
Spring Security的两个主要目标是“认证”和“授权”(访问控制)。
- “认证”(Authentication)
- “授权” (Authorization)
🎆加入坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
做一个认证,做一个授权
// 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");
// 没有权限默认会到登录页面
http.formLogin();
}
// 认证
// 密码编码:PasswordEncoder
// 在spring secuiry 5.0+ 新增了很多的加密方式
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("lzy").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3")
.and()
.withUser("gzw").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
}
这里的授权认证的账号密码可以自己设置也可以从数据库中读取出来
3、注销及权限控制
简单记录一下狂神的注销及权限控制实现,采用的技术的
thymeleaf
+springsecuity
🎆坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
🎆springsecurity配置
// 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");
// 没有权限默认会到登录页面
http.formLogin();
// 注销
http.logout().logoutSuccessUrl("/");
http.csrf().disable(); // 关闭csrf
// .deleteCookies("remove").invalidateHttpSession(true);
}
// 认证
// 密码编码:PasswordEncoder
// 在spring secuiry 5.0+ 新增了很多的加密方式
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("lzy").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3")
.and()
.withUser("gzw").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
}
注意,这里配置注意要关闭
csrf
,并且要高版本的要使用加密方式
🎆页面编写
<!--登录注销-->
<div class="right menu">
<!--如果没有登录-->
<div sec:authorize="!isAuthenticated()">
<a class="item" th:href="@{/toLogin}">
<i class="address card icon"></i> 登录
</a>
</div>
<div sec:authorize="isAuthenticated()">
<!--如果登录:用户名,注销-->
<!--注销-->
<a class="item">
用户名:<span sec:authentication="name"> </span>
角色:<span sec:authentication="principal.authorities"></span>
</a>
</div>
<div sec:authorize="isAuthenticated()">
<!--如果登录:用户名,注销-->
<!--注销-->
<a class="item" th:href="@{/logout}">
<i class="sign-out icon"></i> 注销
</a>
</div>
</div>
<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">
<div class="ui raised segment" sec:authorize="hasRole('vip2')">
<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">
<div class="ui raised segment" sec:authorize="hasRole('vip3')">
<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>
通过导入thymeleaf-extras-springsecurity4包,可以使用一些语法,通过用户角色来显示权限
注意如果使用不了,是因为springboot的版本太高,建议使用2.0.9.RELEASE
4、记住我及首页定制
🎆springsecurity配置
// 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");
// 没有权限默认会到登录页面
http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");
// 注销
http.logout().logoutSuccessUrl("/");
http.csrf().disable(); // 关闭csrf
// .deleteCookies("remove").invalidateHttpSession(true);
// 开启记住我功能 默认存储两周 自定义接受前端的参数
http.rememberMe().rememberMeParameter("remember");
}
// 认证
// 密码编码:PasswordEncoder
// 在spring secuiry 5.0+ 新增了很多的加密方式
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("lzy").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3")
.and()
.withUser("gzw").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
}
💬新配置
http.formLogin().loginPage(“/toLogin”).usernameParameter(“user”).passwordParameter(“pwd”).loginProcessingUrl(“/login”);
- loginPage就是修改了默认的登录页面(首页定制)
- usernameParameter和passwordParameter
这里要注意和页面传过来的name一致
- loginProcessingUrl就是校验逻辑从这里走
http.rememberMe().rememberMeParameter(“remember”);
- 记住密码,注意后面那个要和页面那个一致