springboot
什麼是springboot
配置如何編寫 yaml
自動裝配原理
集成web開發:業務核心
集成數據庫Druid
分佈式開發: Dubbo(RPC)+zookeeper
swagger:接口文檔
任務調度
springSecurity:Shiro
springcloud
微服務
springcloud入門
Restful
Eureka
Ribbon
Feign
HyStrix
Zuul 路由網關
Spring Cloud Config:git
springboot 一站式開發框架 1.5.9 版本
springboot 主要優點:開箱即用,內嵌tomcat ,沒有xml配置要求
springboot 是打成 jar 包運行的
springboot 構建一個功能獨立的微服務應用單元,快速構建一個應用
springCloud 大型分佈式網絡服務的調用,實現分佈式
springCloudDataFlow 在分佈式中間,進行流數據的計算處理。
maven - gav 定位一個jar 包位置
springboot maven 中 artifactid 都是以spring - boot - starter - 開頭
spring - boot - starter - web 用實現 Http 接口 (該接口包含了 springMvc) 使用tomcat 作爲默認嵌入容器
要在springboot Application 文件同級目錄下建立controller、dao 。。。。才能開始測試,
如圖:
創建springboot 項目
1. 利用官方提供的項目
去官網配置並下載:https://spring.io/projects/spring-boot
配置時 記得要添加 web 組件
導入maven項目,
總結:啥配置都不用寫,可以把更多的精力放在業務上
2.利用 IDEA 模板創建
添加依賴 也可以到maven -- pom 裏面添加
創建後的目錄
//創建controller
到此 創建完成,什麼配置都不用添加,也不用配置tomcat ,直接訪問 http://localhost:8080/test
修改springboot 啓動時的 banner
字符圖片生成網站(banner生成網站): https://www.bootschool.net/ascii
去該網站下生成文件,保存txt
在 resouce 文件夾下 新建 banner . txt
將內容填充至 該文件中,springboot加載時,會加載該文本,並顯示
需要注意的是,你的配置文件是否被springboot 識別,看文件圖標下,是否有springboot 圖標(類似於電源按鈕圖標)
JSR303數據校驗
@Compant
@Validated //數據校驗
public class Person{
@Email(message="錯誤提示")
private String email;
get 、 set method
}
空檢查
@Null 驗證對象是否爲null
@NotNull 驗證對象是否不爲null, 無法查檢長度爲0的字符串
@NotBlank 檢查約束字符串是不是Null還有被Trim的長度是否大於0,只對字符串,且會去掉前後空格.
@NotEmpty 檢查約束元素是否爲NULL或者是EMPTY.
Booelan檢查
@AssertTrue 驗證 Boolean 對象是否爲 true
@AssertFalse 驗證 Boolean 對象是否爲 false
長度檢查
@Size(min=, max=) 驗證對象(Array,Collection,Map,String)長度是否在給定的範圍之內
@Length(min=, max=) Validates that the annotated string is between min and max included.
日期檢查
@Past 驗證 Date 和 Calendar 對象是否在當前時間之前
@Future 驗證 Date 和 Calendar 對象是否在當前時間之後
@Pattern 驗證 String 對象是否符合正則表達式的規則
數值檢查,建議使用在Stirng,Integer類型,不建議使用在int類型上,因爲表單值爲“”時無法轉換爲int,但可以轉換爲Stirng爲"",Integer爲null
@Min 驗證 Number 和 String 對象是否大等於指定的值
@Max 驗證 Number 和 String 對象是否小等於指定的值
@DecimalMax 被標註的值必須不大於約束中指定的最大值. 這個約束的參數是一個通過BigDecimal定義的最大值的字符串表示.小數存在精度
@DecimalMin 被標註的值必須不小於約束中指定的最小值. 這個約束的參數是一個通過BigDecimal定義的最小值的字符串表示.小數存在精度
@Digits 驗證 Number 和 String 的構成是否合法
@Digits(integer=,fraction=) 驗證字符串是否是符合指定格式的數字,interger指定整數精度,fraction指定小數精度。
@Range(min=, max=) 檢查數字是否介於min和max之間.
@Range(min=10000,max=50000,message="range.bean.wage")
private BigDecimal wage;
@Valid 遞歸的對關聯對象進行校驗, 如果關聯對象是個集合或者數組,那麼對其中的元素進行遞歸校驗,如果是一個map,則對其中的值部分進行校驗.(是否進行遞歸驗證)
@CreditCardNumber 信用卡驗證
@Email 驗證是否是郵件地址,如果爲null,不進行驗證,算通過驗證。
@ScriptAssert(lang= ,script=, alias=)
@URL(protocol=,host=, port=,regexp=, flags=)
本文參與騰訊雲自媒體分享計劃,歡迎正在閱讀的你也加入,一起分享。
將springboot應用打包成jar
maven 依賴
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
這樣在運行項目後,或者 使用 maven-package 命令後 traget 目錄下,就會生成jar包,運行這個jar包,就啓動了服務
springboot 註解介紹
@SpringBootApplication : 表示類爲springboot 的應用
@SpringBootConfiguration : 表示類爲springboot 配置類
@Configuration : 表示爲配置類
@EnableAutoConfiguration : 開啓自動配置功能 ,以前大部分需要配置的東西,都自動配置了
@AutoConfigurationPackage: 自動配置包
@Import : spring 註解,導入組件,會導入許多的自動配置類(xxxAutoConfiguration),並配置好這些組件
@RestController
一般Controller層 有些類全部返回的都是ResponseBody
所以@ResponseBody可以提取到類上,如:
@Controller
@RestController
以上兩個組合寫法
@RestController
項目基本目錄結構
public 、 resources 是自己創建的
static 目錄,用來存放 css,js ,圖片
templates 文件夾,用來存放springmvc 跳轉的頁面,模板引擎頁面
application.properties : springboot 配置文件
yaml (springboot配置文件:刪除application.xml,添加application.yaml)
在以往的配置文件中,一般配置放在 xml 中
但是springboot 推出了一種新得寫法:yaml
剔除掉了 xml 得複雜配置,簡化 xml
但是yaml 對於空格得要求十分得嚴格
換行後加一空格:那麼與上一行得關係就是層級關係了。如果沒有空格:就是同級關係。
格式: [name]: 空格[value]
例子:
值 name: xiongzhenxing
對象sutdent
name: xzx
age: 12
使用yaml 獲取隨機數
user.id=${random.uuid}
user.id=${random.int}
user.id=${random.int(10)}
使用yaml 直接注入數組、List、Set
pets:
- cat
- dog
- pig
或者
pets: [cat,dog,pib]
使用 yaml 直接注入對象 (使用情況:工程可能存在得配置類)
entity--》Person
@Component
@ConfigurationProperties( prefix ="person")
public Class Person{
private String name;
private Integer age;
private Data sendTimd;
get 、 set (method)
}
application.yaml
person:
name: xiongzhenxing
age: 12
sendTime: 2020/2/18
或者
person: {name: xiongzhenxing,age: 12,sendTime: 2020/2/18}
使用ConfigurationProperties 註解得時候,可能會存在報紅
pom.xml 添加dependency
<dependency>
<groupId>org.springframework.boot></groupId>
<artifactId>spring-boot-configuration-processor</artifactld>
<optional>true</optional>
</dependency>
spring boot 多環境配置,加載指定 application 文件
在實際開發中,可能存在多套配置,如何在切換配置文件?
1.(假設下面得文件後綴爲yaml)
默認加載 application.yaml , 那麼可以在 application.yaml 中配置
spring:
profiles:
active: test
2. 多個配置寫在一個文件中,只有一個配置文件 applicaiotn.yaml
server:
port: 8080
spring:
profiles:
active: test #如果不寫spring。profiles.active..這些,就默認加載第一個配置
--- #作爲多環境分割
server:
port: 8081
spring:
profiles: dev
---
server:
port: 8082
spring:
profiles: test
當項目打包成jar 後,可以通過啓動命令選擇指定的配置
1.java -jar xx.jar --spring.profiles.active=dev
2.可以在jar 包所在目錄,創建application.properties 配置
以上兩種,優先級都高於所有
使用 PropertySource 加載指定其他的配置文件(除application以外的)
@Component
@PropertySource( value= "classpath:xx.properties")
public Class Person{
private String name;
private Integer age;
private Data sendTimd;
get 、 set (method)
}
導入用戶自定義的spring配置文件 ImportResource
使其文件內容生效,在main 方法所在主類 前面加上註解,並且指定 配置文件
@ImportResource(locations = {"classpath: xxbeansxx.xml"})
@SpringBootApplication
public class SpringbootDay01Application {
public static void main(String[] args) {
SpringApplication.run(SpringbootDay01Application.class, args);
}
}
這樣 用戶自定義spring配置文件 xxbeansxx.xml 中的配置內容就生效了
但是springboot 不推薦使用配置,所以這種方法不常用,看下面的 spring代碼配置類
添加 spring 配置類 @Configuration
指明當前類是一個spring配置類,來替代 spring配置文件
添加註解 @Configuration
1. 註冊bean對象
方法名稱 就是 bean 對象名
返回值及返回類型,就是 bean 類型
@Bean
public HelloService helloService(){
return new HelloSerivce(); //返回值及返回類型,就是 bean 類型
}
springboot 日誌 SLF4j+ logback
springboot 使用的是 SLF4j + logback 並且使用了許多日誌接口,兼容了其他日誌如log4j,commons等
SLF4j 是日誌接口,logback 是日誌實現
Logger logger = LoggerFactory.getLogger(getClass());
日誌級別 (由低到高)
logger.trace("");
logger.debug("");
logger.info("");
logger.warn("");
logger.error("");
調整日誌級別 , 日誌只會在當前級別與更高級別生效,低級別就不會生效
springboot 默認日誌級別 : info
調整某個包或者類得日誌級別,其他默認 ,在application.properties 中配置
logging.level.com.xx=trace
指定日誌文件: 如上圖
指定日誌文件路徑:如上圖
控制檯日誌輸出格式:logging.pattern.console=%d{yyyy-MM-dd} [%thread] %-5level %logger{50} - %msg%n
文件日誌輸出格式:logging.pattern.file=%d{yyyy-MM-dd} [%thread] %-5level %logger{50} - %msg%n
如果覺得springboot 日誌配置不符合項目要求
可以在類根路徑下 更具使用得日誌實現,創建相應得日誌配置文件
springboot --- springmvc
編輯 application.properties
#關閉thymeleaf 模板緩存
spring.thymeleaf.cache=false
#修改項目訪問地址
server.servlet.context-path=/xx
#修改項目訪問端口
server.port=xx
#指定國際化文件所在目錄
spring.messages.basename=i18n.login
#修改默認日期格式
spring.mvc.date-format=yyyy/MM/dd
#默認不支持put,delete等請求方式
spring.mvc.hiddenmethod.filter.enabled=true
#修改tomcat字符編碼
server.tomcat.uri-encoding=UTF-8
資源目錄
訪問 資源文件夾,不用加文件夾名稱 ( public 、resources 、static、templates)
靜態資源的訪問
如果自己在application 文件中指定了,靜態資源目錄,那麼默認的自動失效
例如: spring.mvc.static-path-pattern=/file/**
設置首頁
在resources 下的 public 、 resources 、 static 任意目錄中創建 index.html
那麼在訪問主頁 http://localhost:8080/ 時,會加載這個 index.html
但是開發不用這個,因爲index.html 應該放到 themplates 中
所以我們採用 @RequestMapping( { "/","index.html" } ) 這種方式映射
修改網頁圖標
springmvc 版本要求2.1.* 2.2.* 不行
在resources資源文件夾下任意目錄創建 文件 favicon.ico
thymeleaf 請求頁面 ( 或者可以在創建項目的時候直接勾選thymeleaf)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
/*忽略以下內容*/
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
通過controller 方法返回的字符串,即可去 templates 目錄下找 返回字符串.html
從而實現請求到頁面的跳轉
如果想在 頁面使用表達式
需要在 html 標籤中加入命名空間 xmlns:th="http://www.thymeleaf.org
<html lang="en" xmlns:th="http://www.thymeleaf.org">
@Controller
public class testController {
@RequestMapping("test")
public String test(Model model){
model.addAttribute("msg","hello springboot");
return "test";
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="${msg}"> </div>
</body>
</html>
thymeleaf 取值方式
行內寫法 ,沒有標籤 [[ ${變量名} ]]
普通變量 ${...} 可以取作用域值 ${session.user}
國際化消息 #{...}
URL @{...} @{/image/xx.jpg} or @{/image/add ( data=${b} ) }
片段表達式 ~{...} 插入頁面
文本操作 +
數學運算 + - * / % >= <=
布爾運算 and or
條件運算 ( if )?( then ):(else)
thymeleaf 接管標籤詳解
th屬性會替換掉原有得html 屬性 , 例如: <div id = "aaa" th:id="bbb"/> 那麼最後id 爲bbb
th:text 普通文本
model.addAttribute("msg","<h1>hello springboot</h1>");
<div th:text="${msg}"> </div>
th:utext html標籤轉義
model.addAttribute("msg","<h1>hello springboot</h1>");
<div th:utext="${msg}"> </div>
th:each 遍歷數據
th:fragment th:replace 抽取公共頁面(例:頂部導航,底部,側邊)
可以將公共標籤,寫在一個新的html文件中,在需要抽取標籤上加上 th:fragment="xx"
也可以用id 定位到抽取的標籤 ,不過在引入的時候,需要在標籤前加上# 例:~{xx::#xx}
顯示抽取內容
將整個公共頁面插入到聲明得元素中(最外層得div 存在)
<div th:insert="~{抽取頁面名稱(不要後綴) ::抽取標籤xx}"></div>
將公共頁面 替換 聲明的元素(最外層得div 不存在) 優先選擇這個。。。。。。
<div th:replace="~{抽取頁面名稱(不要後綴) ::抽取標籤xx}"></div>
抽取公共 導航欄,後解決不同頁面高亮顯示
例如在:emps 頁面引入導航欄時加上參數 activeOn,同理在index 頁面,加入參數 index
<div th:replace="~{commons/commons::leftCommons(activeOn='emps')}"/>
在公共導航欄 中判斷,傳遞的 activeOn參數是否等於當前按鈕,等於即高亮
<li th:class="${activeOn=='emps'?'active':''}">
<a href="emps.html"><i class="icon-chevron-right"></i> 表格</a>
</li>
springboot 配置 springmvc @Configuration
在配置類中,添加 springmvc 配置註解 替代 springmvc 配置文件
添加註解 @Configuration
實現接口 WebMvcConfigurer
就可以重寫 springmvc 中封裝的方法
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
標記註解Configuration
實現WebMvcConfigurer接口重寫方法
}
return "redirect:/xx" ; 重定向到某個請求
return "forward:/xx" ; 重定向到某個請求
視圖解析器
當請求來了後, 會優先選擇Controller 匹配,如果匹配成功後,就會根據 返回值 跳轉到指定 html 頁面
如果匹配不成功,就會到視圖解析器 匹配
所以 視圖解析器 得優先級 低於 Controller
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//添加主頁視圖控制
registry.addViewController("/").setViewName("index");
registry.addViewController("/index").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
registry.addViewController("/login").setViewName("login");
registry.addViewController("/login.html").setViewName("login");
}
Interceptors 攔截器
//登錄請求
@RequestMapping( {"/user/login" , "/user/login.html" } )
public String login(@RequestParam("username")String username, @RequestParam("password")String password, Model model, HttpSession session){
if( !StringUtils.isEmpty(username) && "123456".equals(password) ){
session.setAttribute("loginFlag",username);
return "redirect:/index.html";
}else {
model.addAttribute("msg","用戶名或密碼錯誤");
return "login.html";
}
}
//重寫攔截器
public class UserHandlerInterceptors implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object loginFlag = request.getSession().getAttribute("loginFlag");
if(loginFlag!=null){
System.out.println("攔截器放行");
return true;
}else {
System.out.println("攔截器攔截");
request.setAttribute("msg","沒有權限,請登錄!");
request.getRequestDispatcher("/login.html").forward(request,response);
return false;
}
}
}
//攔截器配置
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new UserHandlerInterceptors()) //指定攔截器
.addPathPatterns("/**") //攔截請求
.excludePathPatterns("/login.html","/login","","/assets/**","/bootstrap/**","/images/**","/vendors/**"); //排除請求
}
國際化
1.創建國際化配置文件 i18n/login.properties , i18n/login_zh_CN.properties , i18n/login_en_US.properties
注意 zh_CN 代表中文,en_US 代表英文
2.配置文件中指定國際化文件所在目錄
spring.messages.basename=i18n.login
3.修改文件編碼 防止亂碼
4.編寫配置文件
5.將配置得參數 通過國際化寫法 嵌入到頁面
此時,頁面基本上可以跟隨瀏覽器語言得改變,所改變語言
6. 在頁面底部 添加修改語言 鏈接
<a th:href="@{/login.html(language='zh_CN')}"> 中文</a>
<a th:href="@{/login.html(language='en_US')}"> 英文</a>
7. 重寫區域解析器
package com.nextstep.component;
import org.springframework.web.servlet.LocaleResolver;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
//在連接上攜帶區域信息 http://localhost:8080/login.html?language=zh_CN
//還要將該容器添加到 Bean 中
public class MyLocaleResolver implements LocaleResolver {
//區域解析器
@Override
public Locale resolveLocale(HttpServletRequest request) {
String language = request.getParameter("language"); //獲取地區 language 參數
Locale locale = Locale.getDefault(); // 默認
if(!StringUtils.isEmpty(language)){ //傳值是否爲空
String[] split = language.split("_"); //分割 en_US ch_CN
locale = new Locale(split[0],split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
8.將區域解析器,添加到springmvc 中
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
//區域解析器
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
}
結構
即可通過 鏈接來修改頁面語言
Restful 風格 CRUD
1. 查詢所有員工 (/emps) get
//查詢所有員工
@GetMapping({"emps","emps.html"})
public String select(Model model){
List lists = employeeDao.select();
model.addAttribute("lists",lists);
return "emps";
}
<tr th:each="list:${lists}">
<td th:text="${list.id}"></td>
<td >[[${list.lastName}]]</td>
</tr>
2.查詢某個員工--修改頁面 (/emp/1) get
<a th:href="@{/emp/}+${list.id}">修改</a>
//修改員工頁面
@GetMapping("emp/{id}")
public String updateEmpPage(@PathVariable("id") Integer id , Model model){
Employee employee = employeeDao.selectById(id);
model.addAttribute("updateEmp",employee);
return "update";
}
<form class="form-horizontal" method="post" th:action="@{/emp}">
<input th:type="hidden" name="_method" value="put">
<input class="input-xlarge focused" name="lastName" type="text" th:value="${updateEmp.lastName}">
<button type="submit" class="btn btn-primary">修改</button>
</form>
6.修改員員工信息 (/emp) put
//修改員工
@PutMapping("emp")
public String updateEmp(Employee employee){
logger.info("logger--put Emp");
employeeDao.update(employee);
return "redirect:/emps";
}
3. 來到添加員工信息頁面 (/emp) get
//添加員工頁面
@GetMapping("emp")
public String addEmpPage(){
return "add";
}
<form class="form-horizontal" th:method="post" th:action="@{emp}">
<input class="input-xlarge focused" name="lastName" type="text" >
</form>
4. 添加員工 (/emp) post
//添加員工請求
@PostMapping("emp")
public String addEmp(Employee employee){
employee.setId(123);
employeeDao.add(employee);
logger.info("logger--post Emp");
return "redirect:/emps";
}
7. 刪除員工 (/emp/1) delete
<form th:action="@{/emp/}+${list.id}" method="post">
<input type="hidden" name="_method" value="DELETE">
<input type="submit" value="刪除"></a>
</form>
//刪除員工
@DeleteMapping("emp/{id}")
public String deleteEmp(@PathVariable("id") Integer id ){
employeeDao.delete(id);
return "redirect:/emps";
}
定製錯誤頁面
1.在模板引擎themplates 下創建 error 文件夾
2.在error文件夾下創建對應的錯誤碼頁面 例: 404.html , 405.html , 500.html
3.可以使用通用錯誤頁面 4xx.html , 5xx.html 優先精確匹配
可以在錯誤頁面獲取的信息
1.timestamp:時間戳
2.status:狀態碼
3.error:錯誤提示
4.exception:異常對象
5.message:異常信息
6.errors:JSR303 數據校驗錯誤
錯誤信息的頁面獲取用法 : <h1> [[ ${ status } ]]
修改 默認 servlet 容器
修改默認容器爲 jetty,在application.properties 中的配置還是一樣的
排除掉 tomcat 依賴,添加 jetty 依賴, 在底層會自動判斷容器是否存在,存在就加載
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starters-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>