SpringBoot
1.SpringBoot : Hello World !
使用https://start.spring.io/ Spring Initializr 创建
配置基本内容 下载jar包 用IDEA打开
2.用IDEA创建SpringBoot集成式开发环境
微服务架构就是把一个一个的服务拆成jar 相互可以有关系,但没有耦合,前端或者客户端就提供数据,后端来存储即可,逻辑清晰后,自动化微服务。
修改maven 阿里云镜像
maven/conf/settings.xml
<mirrors>
<mirror>
<id>alimaven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
一键启动 + 热部署 不知道比原生的Tomcat快了(乐)多少倍
热部署:。。。
SpringBoot配置原理:
改Server配置:
端口号 :server.port:8000
springboot-banner
更改艺术字:
https://www.bootschool.net/ascii
自由定制
SpringBoot原理
自动配置
完全依赖于父工程所有文件
spring-boot-starter-web
主启动类 启动所有
标注这个类为Spring Application
@SpringBootConfiguration
@Configuration
@Cmponent
@EnableAutoConfiguration
@AutoConfigurationPackage
@Import
.....
yaml YAML Ain't a Markup Language
关于语言规范:我已经用yaml 写了一篇swagger2文档
配置文件
application.yaml 官方推荐
application.properties
传统的Spring注入方式
@Component
@Autowired
@Qualifier
现在SpringBoot用yaml 注入方式
不用yaml配置使用此注解(@ConfigurationProperties)会爆红
配置属性必须有Component/Controller/Service 等注入注解 这是必须的
元素注解一个一个注入 @AutoWired
yaml引用
application.yaml
dog: &dog #引用 name: rui age: 3
person:
name: yaml
age: 23
happy: true
birth: 2001/02/09
maps: {k1: v1,k2: v2}
lists:
- dog
- cat
- shark
dog: *dog #解引用
不推荐的方式
application.properties
@Component //注册bean
@PropertySource(value = "classpath:user.properties")
public class User {
//直接使用@value
@Value("${user.name}") //从配置文件中取值
private String name;
@Value("#{9*2}") // #{SPEL} Spring表达式
private int age;
@Value("男") // 字面量
private String sex;
}
推荐的方式
application.yaml松散绑定
person:
hello: hello1
name: ${hello: hello2}_name
能找到属性对应了,没找到的属性null 视为松散绑定
.yaml
特性2:松散绑定:对应属性名不一致
.yaml last-name <---> .java (@annotation) lastName
JSR303属性(data数据)校验
类似前端表单校验
可以放置.yaml配置文件的位置
1.优先级顺序:
/config/application.yaml
/application.yaml
/src/main/resources/config/application.yaml
官方默认优先级最低:/src/main/resources/application.yaml
2.生产环境,测试环境
springboot多环境配置:
/*. properties :pspring.profile.active=test
server: port: 8081 spring: profiles: active: dev
server:
port: 8082
spring:
profiles: test
server:
port: 8083
spring:
profiles: dev
问题1/bug1:
绑定.yaml 属性失败:
@Validated 不要随意使用
SpringBoot Web 开发
1.jar : webapp
自动装配
springboot 配置了所哟我们需要的东西,配置可修改,可以修改我们需要的,可扩展。
- xxxAutoConfiguration : 像容器配置组件
- xxxProperties: 自动配置类 ,装配自定义内容
要解决的问题:
- 导入静态资源,html,css,js,bootstrap,Angular.js,React,js,Vue.js....
- 首页定制
- 再无jsp->模板引擎Thymeleaf
- 装配SpringMVC
- CRUD/JDBC/ACID/Transaction
- Interceptor/Filter
- International Realize
2.静态资源:
1.创建新项目
rubbish文件一个一个删除
IDEA小技巧:double SHIFT=search everything
double CTRL= run anything
static :放置静态资源
查看源码 : WebMvcAutoConfiguration.java
webjar直接导入包 不必用jar包下载
resouces:
--public: 1.js
--resources: 1.js
--static: 1.js
优先级: resources ->static -> public
- webjars localhost:port/webjars/
- public ,static ,/**,resources localhost:port/1.js
定制首页/404和图标
resouces:
public: index.html
关于模板引擎Thymeleaf
jsp是一种Tomcat原生模板引擎
Servlet :HTTP/MVC和SpringMVC支持 SpringBoot内嵌式Tomcat不支持jsp
Thymeleaf 模板引擎和启动器
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
<version>3.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
thymeleaf 依赖springboot-thymeleaf ->
public:index.html
templates:test.html
SpringMVC配置原理:
视图解析器:
DIY自定义定制化功能
实现组件 交给springboot spring boot 自动装配了
。。。。定义原理,组件原理,启动原理,再议。。。。
SpringBoot前端伪造后端工程
学到了什么?
- SpringBoot是什么?
- 微服务架构
- Helloworld
- 源码自动装配原理
- yaml学习
- 多文档切换yaml
- Thymeleaf th:xxx前后端交互模板引擎
- SpringBoot 扩展MVC ~config MVC
- 修改SpringBoot默认配置
- CRUD
- 过滤器拦截器
- 页面国际化
- 首页,404 500 ERROR
接下来:
- JDBC
- Mybatis
- Druid
- Shiro:安全
- SpringSecurity:安全
- 异步任务,邮件发送 定时定制 推送广告邮件,短信发送推送消息
- Swagger文档书写
- Dubbo+Zookeeper 分布式架构
- 微服务架构之分布式消息中间件 Kafka消息队列 扎心了老铁
Spring Data
整合CRUD/Mybatis
前端模板引擎小提示
<html lang="en" xmlns:th="http://www.thymeleaf.org">
jdbc基本操作用jdbcTemplate完全实现了
简书文档
https://www.jianshu.com/p/4453368eb716
官方文档
https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.pdf
thymeleaf模板引擎报错
"views/level1/1": An error happened during template parsing (template: "class path resource [templates/views/level1/1.html]" - line 23, col 76)
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/views/level1/1.html]" - line 23, col 76)] with root cause
解决方案:
不可以在一个div内重复定义多个class thymaleaf会显示异常
div 内不能加href 没用 点也没效果
整体引用会出现 Date 不匹配以及不显示的问题 很难看,每一个跳转都要分发Date()
数据源:Druid 德鲁伊
Druid已经在阿里巴巴部署了超过600个应用,经过一年多生产环境大规模部署的严苛考验。
Spring Boot 2.0 以上默认使用 Hikari 数据源,可以说 Hikari 与 Driud 都是当前 Java Web 上最优秀的数据源,我们来重点介绍 Spring Boot 如何集成 Druid 数据源,如何实现数据库监控。
Druid数据源实现web page监控 原生提供页面
报错原因:
xml配置文件 控制文件难逃其咎
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.yml</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.yml</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
spring-boot 虽然不需要xml,也需要config 转义成 .xml文件的配置
@Bean
/config/Druid.java -> .xml 所以需要配置过滤 让他不被过滤掉
SpringBoot 整合Mybatis
整合包 启动器
mybatis-springboot-starter /mybatis Plus
目前位置 完整jar-maven 依赖
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.teams</groupId> <artifactId>springboot-mybatis</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springboot-mybatis</name> <description>Demo project for Spring Boot</description>
<properties> <java.version>14</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>4.5.0</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.5.1</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.23</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-java8time</artifactId> <version>3.0.0.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>
</project>
<resources><!--是这种过滤器-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
application.yaml/druid.java config/
spring: datasource: username: root password: 123456 url: jdbc:mysql://localhost:3306/ssmbuild?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver 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,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
server:
port: 8080
server:
port: 8081
spring:
profiles: dev
server:
port: 8082
spring:
profiles: test
application.yaml mybatis config
spring: datasource: username: root password: 123456 #?serverTimezone=UTC解决时区的报错 url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默认是不注入这些属性值的,需要自己绑定 #druid 数据源专有配置 initialSize: 5 minIdle: 5 maxActive: 20 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入 #如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j filters: stat,wall,log4j maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
一大堆莫名其妙的错误来了
解决方案
1.配置yaml
url: jdbc:mysql://localhost:3306/ssmbuild?serverTimezone=Asia/Shanghai&useSSL=false&useUnicode=true&characterEncoding=utf-8
2.mysql调整世界时区 要Asia/Shanghai 不要UTC
报错显示url问题和静态资源filter没多大关系
错误x1
url错误 :
静态资源错误
mysql时区配置错误
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
Mapper要加
@Mapper
@Repository
然后还是静态资源配置问题 静态资源不要轻易配置
<resources><!--是这种过滤器-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
启动正常!!!2020.08.15/ 22.12.pm
错误x2
ibatis绑定mapper错误
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.teams.mapper.DepartmentMapper.add] with root cause
方案:
目录放置 不和SpringMVC一致了,SpringBoot放在/resources/mybatis/mapper/*Mapper.xml下
发现还是错....
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.teams.mapper.DepartmentMapper.add] with root cause
.yaml .properties 必须整合mybatis....
yaml整合
mybatis:
type-aliases-package: com.teams.pojo
mapper-locations: classpath:mybatis/mapper/*.xml
mybatis传递多个参数
DAO level 《 === 》 Mapper level 持久映射层
第一种方案 DAO层的函数方法 Public User selectUser(String name,String area); 对应的Mapper.xml 其中,#{0}代表接收的是dao层中的第一个参数,#{1}代表dao层中第二参数,更多参数一致往后加即可。
第二种方案 此方法采用Map传多参数. DAO层的函数方法 Public User selectUser(Map paramMap); 对应的Mapper.xml Service层调用 Private User xxxSelectUser(){ Map paramMap=new hashMap(); paramMap.put(“userName”,”对应具体的参数值”); paramMap.put(“userArea”,”对应具体的参数值”); User user=xxx. selectUser(paramMap);}
此方法不够直观,见到接口方法不能直接的知道要传的参数是什么
第三种方案 DAO层的函数方法 Public User selectUser(@param("userName")String name,@param("userArea")String area); 对应的Mapper.xml 这种方法比较好,能让开发者看到dao层方法就知道该传什么样的参数,比较直观,个人推荐用此种方案。
我的想法:遇到一个对象 和一个单参数或多个单参数 controller传值 @PathVarible
果然不行:
threw exception [Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'name' not found. Available parameters are [id, department, param1, param2]] with root cause
类对象全都拆分成参数可行!!!
SpringSecurity
web开发 安全第一 过滤器 拦截器也可做到
漏洞:隐私泄露
安全在设计之初
Shiro+SpringSecurity : 认证,授权(vip1,vip2,vip3)
解决拦截器和过滤器的复杂问题
从蛮荒时代走来:
Servlet--MVC--Spring--SpringMVC--SpringBoot--+(SpringSecurity)--SpringBoot
静态资源:https://blog.csdn.net/wulei2921625957/article/details/108002503
schema选择数据库
Aop思想 拦截
密码加密错误
java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
知识点:SemanticUI
Semantic作为一款开发框架,帮助开发者使用对人类友好的HTML语言构建优雅的响应式布局。
登陆跳转 私人定制化服务
thymeleaf 模板引擎支持私人化定制服务
实现的功能:
已经登陆 有登出按钮
没有登录 有登陆按钮
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
springSecurity整合thymeleaf
这个整合高级定制要降低springboot版本
2.0.9.RELEASE
两个版本整合错误
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: Cannot pass a null GrantedAuthority collection
attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: Cannot pass a null GrantedAuthority collection
版本换为2.0.7后
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userMapper'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userMapper' defined in file [D:\IDEAProject\springsecurity\target\classes\com\teams\dao\UserMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Generic.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: com.mysql.cj.jdbc.Driver
解决方法 >application.yaml
driver-class-name: com.mysql.jdbc.Driver
错误
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: Cannot pass a null GrantedAuthority collection
换为原来的版本
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: Cannot pass a null GrantedAuthority collection
注入bean失败 ?
可能错误 :
- 对应的 bean 没有添加注解;
- 对应的 bean 添加注解错误,例如将 Spring 的
@Service
错选成 dubbo 的; - 选择错误的自动注入方法等。
attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: Cannot pass a null GrantedAuthority collection
方法 /config/.java ----》/xml
若配置文件没有设置配置java bean中的属性值,则配置java bean属性需配置默认值,否则就类似如上报错
@EnableWebSecurity
去掉注解可以跑 不能正常运行
换环境重启 重新跑起来
失败的好彻底...
17:39:52.770 [main] DEBUG org.springframework.boot.context.logging.ClasspathLoggingApplicationListener - Application failed to start with classpath: unknown 17:39:52.773 [main] ERROR org.springframework.boot.SpringApplication - Application run failed java.lang.IllegalStateException: Failed to load property source from 'file:/D:/IDEAProject/springboot-fucking/target/classes/application.yaml' (classpath:/application.yaml) at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.load(ConfigFileApplicationListener.java:553) at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.loadForFileExtension(ConfigFileApplicationListener.java:498) at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.load(ConfigFileApplicationListener.java:468) at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.lambda$null$7(ConfigFileApplicationListener.java:447) at java.base/java.lang.Iterable.forEach(Iterable.java:75) at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.lambda$load$8(ConfigFileApplicationListener.java:447) at java.base/java.lang.Iterable.forEach(Iterable.java:75) at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.load(ConfigFileApplicationListener.java:444) at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.lambda$load$0(ConfigFileApplicationListener.java:347) at org.springframework.boot.context.config.FilteredPropertySource.apply(FilteredPropertySource.java:54) at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.load(ConfigFileApplicationListener.java:335) at org.springframework.boot.context.config.ConfigFileApplicationListener.addPropertySources(ConfigFileApplicationListener.java:226) at org.springframework.boot.context.config.ConfigFileApplicationListener.postProcessEnvironment(ConfigFileApplicationListener.java:210) at org.springframework.boot.context.config.ConfigFileApplicationListener.onApplicationEnvironmentPreparedEvent(ConfigFileApplicationListener.java:200) at org.springframework.boot.context.config.ConfigFileApplicationListener.onApplicationEvent(ConfigFileApplicationListener.java:188) at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172) at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165) at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139) at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:127) at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:80) at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:53) at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:345) at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) at fucking.pom.SpringbootFuckingApplication.main(SpringbootFuckingApplication.java:10) Caused by: org.yaml.snakeyaml.error.YAMLException: java.nio.charset.MalformedInputException: Input length = 1 at org.yaml.snakeyaml.reader.StreamReader.update(StreamReader.java:218) at org.yaml.snakeyaml.reader.StreamReader.ensureEnoughData(StreamReader.java:176) at org.yaml.snakeyaml.reader.StreamReader.ensureEnoughData(StreamReader.java:171) at org.yaml.snakeyaml.reader.StreamReader.peek(StreamReader.java:126) at org.yaml.snakeyaml.scanner.ScannerImpl.scanToNextToken(ScannerImpl.java:1177) at org.yaml.snakeyaml.scanner.ScannerImpl.fetchMoreTokens(ScannerImpl.java:287) at org.yaml.snakeyaml.scanner.ScannerImpl.checkToken(ScannerImpl.java:227) at org.yaml.snakeyaml.parser.ParserImpl$ParseImplicitDocumentStart.produce(ParserImpl.java:195) at org.yaml.snakeyaml.parser.ParserImpl.peekEvent(ParserImpl.java:158) at org.yaml.snakeyaml.parser.ParserImpl.checkEvent(ParserImpl.java:148) at org.yaml.snakeyaml.composer.Composer.checkNode(Composer.java:82) at org.yaml.snakeyaml.constructor.BaseConstructor.checkData(BaseConstructor.java:123) at org.yaml.snakeyaml.Yaml$1.hasNext(Yaml.java:489) at org.springframework.beans.factory.config.YamlProcessor.process(YamlProcessor.java:200) at org.springframework.beans.factory.config.YamlProcessor.process(YamlProcessor.java:164) at org.springframework.boot.env.OriginTrackedYamlLoader.load(OriginTrackedYamlLoader.java:76) at org.springframework.boot.env.YamlPropertySourceLoader.load(YamlPropertySourceLoader.java:50) at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.loadDocuments(ConfigFileApplicationListener.java:607) at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.load(ConfigFileApplicationListener.java:523) ... 25 common frames omitted Caused by: java.nio.charset.MalformedInputException: Input length = 1 at java.base/java.nio.charset.CoderResult.throwException(CoderResult.java:274) at java.base/sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:352) at java.base/sun.nio.cs.StreamDecoder.read(StreamDecoder.java:188) at java.base/java.io.InputStreamReader.read(InputStreamReader.java:181) at org.yaml.snakeyaml.reader.UnicodeReader.read(UnicodeReader.java:125) at org.yaml.snakeyaml.reader.StreamReader.update(StreamReader.java:183) ... 43 common frames omitted
Process finished with exit code 1
直接启动spring-security不配置 一个controller ->hello 也会拦截
看控制台信息 然后走secret
控制台信息
started by Juminiy in D:\IDEAProject\springsecurity-02demo)
Using generated security password: 553bcc06-5c89-4f9d-a4d2-cd8f6ab633bb
Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@44d64d4e, org.springframework.security.web.context.SecurityContextPersistenceFilter@6ca8fcf3, org.springframework.security.web.header.HeaderWriterFilter@3d1f558a, org.springframework.security.web.csrf.CsrfFilter@31e130bf, org.springframework.security.web.authentication.logout.LogoutFilter@2b0b7e5a, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@1a500561, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@11f9535b, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter@1dd74143, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@7c781c42, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@66933239, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@41a374be, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@526a9908, org.springframework.security.web.session.SessionManagementFilter@28f4f300, org.springframework.security.web.access.ExceptionTranslationFilter@6e4599c0, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@7f9fc8bd]
默认
account: user
password: RandomUniqueString
看到浏览器session 删除后需要重新登录
我被教程坑了,不需要换版本就可以 ,我为什么脑残换版本???
我的版本就是私人定制。。。
多走些弯路 才能知道什么是真理///
这不就是我想要的吗?
结论:登录成功后,将cookie发送给浏览器保存,以后登录带上这个cookie,只要通过检查就可以免登录了。如果点击注销,则会删除这个cookie,具体的原理我们在JavaWeb阶段都讲过了,这里就不在多说了!
私人定制login:方式必须为post🆗
okokok!!!
整合数据库mybatis
古鲁奇
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.hua.dao.UserMapper.add
junit报错立即停止过滤古鲁奇
UserMapper里边的class type alias正确额
SpringSecurity整合DB走起
是什么?
Spring Security是一个提供身份验证,授权和保护以防止常见攻击的框架。凭借对命令式和响应式应用程序的一流支持,它是用于保护基于Spring的应用程序的事实上的标准
2020.08.18 log 注册功能不可以注册
An internal error occurred while trying to authenticate the user.
org.springframework.security.authentication.InternalAuthenticationServiceException: UserDetailsService returned null, which is an interface contract violation
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:110) ~[spring-security-core-5.3.4.RELEASE.jar:5.3.4.RELEASE]
CSRF(跨站请求伪造)
现在系统中登陆的用户要转账
HTML
<form method="post" action="/transfer">
<input type="text" name="amount"/>
<input type="text" name="routingNumber"/>
<input type="text" name="account"/>
<input type="submit" value="Transfer"/>
</form>
HTTP
POST /transfer HTTP/1.1 Host: bank.example.com Cookie: JSESSIONID=randomid Content-Type: application/x-www-form-urlencoded
amount=100.00&routingNumber=1234&account=9876
现在有个恶意的网站 伪造银行站点 恶意获取你的信息,盗取你的财产
<form method="post" action="https://bank.example.com/transfer">
<input type="hidden" name="amount" value="100.00"/>
<input type="hidden" name="routingNumber" value="evilsRoutingNumber"/>
<input type="hidden" name="account" value="evilsAccountNumber"/>
<input type="submit" value="Win Money!"/>
</form>
您想赢钱,因此单击“提交”按钮。在此过程中,您无意中将$ 100转让给了恶意用户。发生这种情况的原因是,尽管恶意网站无法看到您的cookie,但与您的银行关联的cookie仍与请求一起发送。
最糟糕的是,使用JavaScript可以使整个过程自动化。这意味着您甚至不需要单击按钮。此外,当访问遭受XSS攻击的诚实站点时,也很容易发生这种情况。那么,我们如何保护用户免受此类攻击呢?
隐式传输
<form method="post" action="/transfer">
<input type="hidden" name="_csrf" value="4bfd1575-3ad1-4d21-96c7-4ef2d9f86721"/>
<input type="text" name="amount"/>
<input type="text" name="routingNumber"/>
<input type="hidden" name="account"/>
<input type="submit" value="Transfer"/>
</form>
POST /transfer HTTP/1.1 Host: bank.example.com Cookie: JSESSIONID=randomid Content-Type: application/x-www-form-urlencoded
amount=100.00&routingNumber=1234&account=9876&_csrf=4bfd1575-3ad1-4d21-96c7-4ef2d9f86721
配置太复杂了 我们用Shiro精简一下
pom.xml
导包列表
<dependencies> <!--类启动器--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--jdbc启动器--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--mybatis整合springboot--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency>
<!--前端工具--> <dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>4.5.0</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.5.1</version> </dependency> <!--德鲁伊--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.23</version> </dependency> <!--日志工厂--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!--模板引擎整合--> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity5</artifactId> <version>3.0.4.RELEASE</version> </dependency> <!--金色之屎--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!--mysql连接--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-java8time</artifactId> <version>3.0.0.RELEASE</version> </dependency> <!--junit-test三件套--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <!--古鲁奇:mybatis专用--> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
数据库连接的方法
Spring-Security 整合 Mybatis
页面国际化
1.IDEA Setting FileEncoding UTF-8全部都是
2./resources/i18n/Resource Bundle 'login'
/login.properties
/login_en_US.properties
/login_zh_CN.properties
。。。。
login.btn=登录
login.password=密码
login.tip = 请登录
login.username=用户名
remeber\ me=记住我
login.banner=首页
3.application.yaml 配置
spring:
messages:
basename: i18n.login
4.thymeleaf前端引擎
<a class="item" th:href="@{/index}" th:text="#{login.tip}">首页</a>
....等一下 我先把基本功能完成
2020.08.17 18:54
页面国际化
定制专属404页面
图片格式不匹
错误
@Controller("/userInfo")
SpringBoot 项目打包发布在公网服务器上
1.package
2.本机跑 java -jar xxx.jar
出现本机跑java与服务器版本不一致问题
改变项目结构和java版本
/project
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<java.version>8</java.version>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
/build
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
实际上只需改动
<properties>
<java.version>8</java.version>
</properties>
然后运行 不会自动停止
Exception in thread "main" java.lang.UnsupportedClassVersionError: com/hua/Springsecurity02demoApplication has been compiled by a more recent version of the Java Runtime (class file version 58.0), this version of the Java Runtime only recognizes class file versions up to 52.0
虽然的SpringMVC配置过于复杂 但是Boot还是可以借鉴操作
JDK安装成功
德鲁伊数据库连接池报错
2020-08-18 22:04:10.072 ERROR 31469 --- [nio-8080-exec-1] c.a.druid.pool.DruidAbstractDataSource : discard long time none Asia/Shanghai&useUnicode=true&characterEncoding=utf-8, jdbcUrl : jdbc:mysql://localhost:3306/security?serverTimezone=Asia/S
java -jar xxx.jar
自动化启动
权限控制
chmod 777 xxx.jar
创建软连接到 init.d
ln -s /www/server/springsecurity-02demo-0.0.1-SNAPSHOT.jar /etc/init.d/login
service login start #启动
service login stop #停止
service login status #查看状态
sudo upate-rc.d myproject defaults #开机启动
sudo reboot #重启服务器 代价很大,远程主机不要轻易尝试
SpringBoot+Swagger导出接口文档
导入jar包
然后写/config
提到IDEA下载jar包速度
IDEA的maven下载jar包速度很慢解决办法
右击项目->选择maven->选择open setting或者create setting 将下面代码复制进去然后保存
<?xml version="1.0" encoding="UTF-8"?> <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"> <mirrors> <!-- mirror Specifies a repository mirror site to use instead of a given repository. The repository that this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used for inheritance and direct lookup purposes, and must be unique across the set of mirrors. <mirror> <id>mirrorId</id> <mirrorOf>repositoryId</mirrorOf> <name>Human Readable Name for this Mirror.</name> <url>http://my.repository.com/repo/path</url> </mirror> -->
<mirror> <id>alimaven</id> <name>aliyun maven</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> <mirrorOf>central</mirrorOf> </mirror> <mirror> <id>uk</id> <mirrorOf>central</mirrorOf> <name>Human Readable Name for this Mirror.</name> <url>http://uk.maven.org/maven2/</url> </mirror> <mirror> <id>CN</id> <name>OSChina Central</name> <url>http://maven.oschina.net/content/groups/public/</url> <mirrorOf>central</mirrorOf> </mirror> <mirror> <id>nexus</id> <name>internal nexus repository</name> <!-- <url>http://192.168.1.100:8081/nexus/content/groups/public/</url>--> <url>http://repo.maven.apache.org/maven2</url> <mirrorOf>central</mirrorOf> </mirror> </mirrors>
</settings>
3.0Sswagger-ui 访问 swagger-ui.html方法
springfox jar包
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
SpringFox 3.0.0(包含springfox-swagger2-3.0.0)中访问地址由/swagger-ui.html变成/swagger-ui/index.html
找到版本 对应上去 看源码
io.springfox:springfox-boot-starter:3.0.0
找到SwaggerUiWebMvcConfigurer类
我就访问不了这3.0.0swagger-springfox-io
退回版本2.7 太丑
2.9.2版本稳定 UI 还行
现在我要在生产测试时候加入swagger 任何人凭借端口都能访问 但是上线就不要暴露接口文档swagger 了 那么我们这样做
没有权限了
😱 Could not render e, see the console.
SpringBoot+Security+Swagger 文档权限管理+前后端联调API
无数据库版本
//内存中 现写的 我们要db的 单机版 auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3","admin") .and() .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3") .and() .withUser("juminiy").password(new BCryptPasswordEncoder().encode("qpmz111222@@@")).roles("vip1","vip2") .and() .withUser("liming").password(new BCryptPasswordEncoder().encode("liming123")).roles("vip1");
API文档内部配置token
https://www.jianshu.com/p/3122977af5a4
SpringBoot静态资源配置方法
Spring Boot中静态资源访问的默认配置
在Spring Boot项目中,静态资源和页面文件都统一放在src/main/resources/static或者src/main/resources/public目录下对应的文件夹中
一般src/main/resources/static目录用于存放各类静态资源文件,例如css、js和image等。src/main/resources/templates用于存放页面文件,例如html,jsp等。
如果不使用thymeleaf、FreeMaker、Velocity,不讲将index.html页面放在在src/main/resources/templates,只能放在src/main/resources/static目录下面或者src/main/resources/public目录下面
我们通过查看sping boot的源代码可以发现。系统默认我们配置了static和public路径。重点是”classpath:/META-INF/resources/”, “classpath:/resources/”, “classpath:/static/”, “classpath:/public/”
所以我找到了静态资源的解决方法
/resources/application.properties 放置静态资源链接 用thymeleaf 模板引擎能点进去
即可用
spring.mvc.static-path-pattern=/static/**
所有静态资源顺利导入
springboot中引入静态资源路径问题Failed to load resource: the server responded with a status of 404 ()
*静态资源的的当前路径是在static下,springboot是约定高于配置,约定静态资源的当前路径在static下,所以开始路径为static的下级开始即可
重启IDEA dump->
这就好用了? 为什么 太坑了
https://blog.csdn.net/YiQieFuCong/article/details/85009401
Spring整合Shiro
10分钟入门
Apache Java安全权限框架
Shiro qucikstart于新版本不匹配
原版本的ini.*Factory已经废弃了
Realm iniRealm= new IniRealm("classpath:shiro.ini") ;
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
defaultSecurityManager.setRealm(iniRealm); SecurityUtils.setSecurityManager(defaultSecurityManager);
pm.xml导包 shiro三大部件
Subject
SecurityManager
Realm
没有这句会报错
bean.setSecurityManager(defaultWebSecurityManager);
企业邮箱密码:RedisZookeeper2
没有任何进程8000 却显示被占用....
Web server failed to start. Port 8000 was already in use.
Action:
Identify and stop the process that's listening on port 8000 or configure this application to listen on another port.
cmd
#端口占用情况
netstat -ano
#具体的端口
netstat -aon|findstr "8000"
#发现父亲PID 找到xxx.exe
tasklist|findstr ""
#杀死进程
taskkill /im xxx.exe /f
并没有被占用....
查看相关文档,解决问题