SpringBoot


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/

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>
&lt;properties&gt;
    &lt;java.version&gt;14&lt;/java.version&gt;
&lt;/properties&gt;

&lt;dependencies&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-data-jdbc&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-jdbc&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-thymeleaf&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.mybatis.spring.boot&lt;/groupId&gt;
        &lt;artifactId&gt;mybatis-spring-boot-starter&lt;/artifactId&gt;
        &lt;version&gt;2.1.3&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;dependency&gt;
        &lt;groupId&gt;org.webjars&lt;/groupId&gt;
        &lt;artifactId&gt;bootstrap&lt;/artifactId&gt;
        &lt;version&gt;4.5.0&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.webjars&lt;/groupId&gt;
        &lt;artifactId&gt;jquery&lt;/artifactId&gt;
        &lt;version&gt;3.5.1&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;com.alibaba&lt;/groupId&gt;
        &lt;artifactId&gt;druid&lt;/artifactId&gt;
        &lt;version&gt;1.1.23&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;log4j&lt;/groupId&gt;
        &lt;artifactId&gt;log4j&lt;/artifactId&gt;
        &lt;version&gt;1.2.17&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.thymeleaf&lt;/groupId&gt;
        &lt;artifactId&gt;thymeleaf-spring5&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.thymeleaf.extras&lt;/groupId&gt;
        &lt;artifactId&gt;thymeleaf-extras-java8time&lt;/artifactId&gt;
        &lt;version&gt;3.0.0.RELEASE&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;mysql&lt;/groupId&gt;
        &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
        &lt;scope&gt;runtime&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;
        &lt;artifactId&gt;lombok&lt;/artifactId&gt;
        &lt;optional&gt;true&lt;/optional&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
        &lt;scope&gt;test&lt;/scope&gt;
        &lt;exclusions&gt;
            &lt;exclusion&gt;
                &lt;groupId&gt;org.junit.vintage&lt;/groupId&gt;
                &lt;artifactId&gt;junit-vintage-engine&lt;/artifactId&gt;
            &lt;/exclusion&gt;
        &lt;/exclusions&gt;
    &lt;/dependency&gt;
&lt;/dependencies&gt;

&lt;build&gt;
    &lt;plugins&gt;
        &lt;plugin&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
        &lt;/plugin&gt;
    &lt;/plugins&gt;
    &lt;resources&gt;
        &lt;resource&gt;
            &lt;directory&gt;src/main/java&lt;/directory&gt;
            &lt;includes&gt;
                &lt;include&gt;**/*.xml&lt;/include&gt;
            &lt;/includes&gt;
            &lt;filtering&gt;true&lt;/filtering&gt;
        &lt;/resource&gt;
    &lt;/resources&gt;
&lt;/build&gt;

</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 刪除后需要重新登錄

 

我被教程坑了,不需要換版本就可以 ,我為什么腦殘換版本???

我的版本就是私人定制。。。

多走些彎路 才能知道什么是真理///

這不就是我想要的嗎?

image-20200816184123693

image-20200816184251534

結論:登錄成功后,將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>
    &lt;!--前端工具--&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.webjars&lt;/groupId&gt;
        &lt;artifactId&gt;bootstrap&lt;/artifactId&gt;
        &lt;version&gt;4.5.0&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.webjars&lt;/groupId&gt;
        &lt;artifactId&gt;jquery&lt;/artifactId&gt;
        &lt;version&gt;3.5.1&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;!--德魯伊--&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;com.alibaba&lt;/groupId&gt;
        &lt;artifactId&gt;druid&lt;/artifactId&gt;
        &lt;version&gt;1.1.23&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;!--日志工廠--&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;log4j&lt;/groupId&gt;
        &lt;artifactId&gt;log4j&lt;/artifactId&gt;
        &lt;version&gt;1.2.17&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;!--模板引擎整合--&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.thymeleaf.extras&lt;/groupId&gt;
        &lt;artifactId&gt;thymeleaf-extras-springsecurity5&lt;/artifactId&gt;
        &lt;version&gt;3.0.4.RELEASE&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;!--金色之屎--&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;
        &lt;artifactId&gt;lombok&lt;/artifactId&gt;
        &lt;optional&gt;true&lt;/optional&gt;
    &lt;/dependency&gt;

    &lt;!--mysql連接--&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;mysql&lt;/groupId&gt;
        &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
    &lt;/dependency&gt;

    &lt;dependency&gt;
        &lt;groupId&gt;org.thymeleaf&lt;/groupId&gt;
        &lt;artifactId&gt;thymeleaf-spring5&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.thymeleaf.extras&lt;/groupId&gt;
        &lt;artifactId&gt;thymeleaf-extras-java8time&lt;/artifactId&gt;
        &lt;version&gt;3.0.0.RELEASE&lt;/version&gt;
    &lt;/dependency&gt;




    &lt;!--junit-test三件套--&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
        &lt;scope&gt;test&lt;/scope&gt;
        &lt;exclusions&gt;
            &lt;exclusion&gt;
                &lt;groupId&gt;org.junit.vintage&lt;/groupId&gt;
                &lt;artifactId&gt;junit-vintage-engine&lt;/artifactId&gt;
            &lt;/exclusion&gt;
        &lt;/exclusions&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
        &lt;artifactId&gt;spring-security-test&lt;/artifactId&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
&lt;/dependencies&gt;




&lt;build&gt;
    &lt;plugins&gt;
        &lt;plugin&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
        &lt;/plugin&gt;
    &lt;/plugins&gt;
    &lt;!--古魯奇:mybatis專用--&gt;
    &lt;resources&gt;
        &lt;resource&gt;
            &lt;directory&gt;src/main/java&lt;/directory&gt;
            &lt;includes&gt;
                &lt;include&gt;**/*.xml&lt;/include&gt;
            &lt;/includes&gt;
            &lt;filtering&gt;true&lt;/filtering&gt;
        &lt;/resource&gt;
    &lt;/resources&gt;
&lt;/build&gt;

<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>
         -->
    &lt;mirror&gt;
        &lt;id&gt;alimaven&lt;/id&gt;
        &lt;name&gt;aliyun maven&lt;/name&gt;
        &lt;url&gt;http://maven.aliyun.com/nexus/content/groups/public/&lt;/url&gt;
        &lt;mirrorOf&gt;central&lt;/mirrorOf&gt;
    &lt;/mirror&gt;

    &lt;mirror&gt;
        &lt;id&gt;uk&lt;/id&gt;
        &lt;mirrorOf&gt;central&lt;/mirrorOf&gt;
        &lt;name&gt;Human Readable Name for this Mirror.&lt;/name&gt;
        &lt;url&gt;http://uk.maven.org/maven2/&lt;/url&gt;
    &lt;/mirror&gt;

    &lt;mirror&gt;
        &lt;id&gt;CN&lt;/id&gt;
        &lt;name&gt;OSChina Central&lt;/name&gt;
        &lt;url&gt;http://maven.oschina.net/content/groups/public/&lt;/url&gt;
        &lt;mirrorOf&gt;central&lt;/mirrorOf&gt;
    &lt;/mirror&gt;

    &lt;mirror&gt;
        &lt;id&gt;nexus&lt;/id&gt;
        &lt;name&gt;internal nexus repository&lt;/name&gt;
        &lt;!-- &lt;url&gt;http://192.168.1.100:8081/nexus/content/groups/public/&lt;/url&gt;--&gt;
        &lt;url&gt;http://repo.maven.apache.org/maven2&lt;/url&gt;
        &lt;mirrorOf&gt;central&lt;/mirrorOf&gt;
    &lt;/mirror&gt;

&lt;/mirrors&gt;

</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

image-20200822163929610

 

 

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

並沒有被占用....

查看相關文檔,解決問題

https://www.4480qpg.net/

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM