??博客x主頁(yè):己不由心王道長(zhǎng)??!
??文章說(shuō)明:spring??
?系列專欄:spring
??本篇內(nèi)容:對(duì)SpringBoot進(jìn)行一個(gè)入門學(xué)習(xí)及對(duì)Thymeleaf模板引擎進(jìn)行整合(對(duì)所需知識(shí)點(diǎn)進(jìn)行選擇閱讀呀~)??
??每日一語(yǔ):在人生的道路上,即使一切都失去了,只要一息尚存,你就沒(méi)有絲毫理由絕望。因?yàn)槭サ囊磺校挚赡茉谛碌膶哟紊蠌?fù)得。??
??作者詳情:作者是一名雙非大三在校生,喜歡Java,歡迎大家探討學(xué)習(xí),喜歡的話請(qǐng)給博主一個(gè)三連鼓勵(lì)。??
?? 交流社區(qū):己不由心王道長(zhǎng)(優(yōu)質(zhì)編程社區(qū))
SpringBoot簡(jiǎn)介
SpringBoot是什么
①Spring Boot是由Pivotal團(tuán)隊(duì)提供的全新框架,其設(shè)計(jì)目的是用來(lái)簡(jiǎn)化新Spring應(yīng)用的初始搭建以及開發(fā)過(guò)程。該框架使用了特定的方式來(lái)進(jìn)行配置,從而使開發(fā)人員不再需要定義樣板化的配置。通過(guò)這種方式,Spring Boot致力于在蓬勃發(fā)展的快速應(yīng)用開發(fā)領(lǐng)域(rapid application development)成為領(lǐng)導(dǎo)者。
為什么要學(xué)習(xí)SpringBoot
一、SpringBoot能簡(jiǎn)化配置、從 2002 年開始,Spring 一直在飛速的發(fā)展,如今已經(jīng)成為了在Java EE(Java Enterprise Edition)開發(fā)中真正意義上的標(biāo)準(zhǔn),但是隨著技術(shù)的發(fā)展,Java EE使用 Spring 逐漸變得笨重起來(lái),大量的 XML 文件存在于項(xiàng)目之中。
SpringBoot的優(yōu)勢(shì)
1、減少開發(fā),測(cè)試時(shí)間和努力。
2、使用JavaConfig有助于避免使用XML。
3、避免大量的Maven導(dǎo)入和各種版本沖突。
4、提供意見(jiàn)發(fā)展方法。
5、通過(guò)提供默認(rèn)值快速開始開發(fā)。
6、沒(méi)有單獨(dú)的Web服務(wù)器需要。這意味著你不再需要啟動(dòng)Tomcat,Glassfish或其他任何東西。
學(xué)習(xí)SpringBoot前要具備的基礎(chǔ)
聲明:這不是在勸退,而是在告訴同志們,學(xué)習(xí)是一個(gè)循序漸進(jìn)的過(guò)程,不可操之過(guò)急。一步一個(gè)腳印的走,才能到達(dá)終點(diǎn)站。
學(xué)習(xí)這個(gè)知識(shí)點(diǎn)你應(yīng)該具備的一些基礎(chǔ)知識(shí):
基礎(chǔ)篇:javase基礎(chǔ),包括但不限于:面向?qū)ο?,封裝,繼承,多態(tài),類與接口,集合,IO等等。
基礎(chǔ)篇:Spring、SpringMVC:知道Spring是用來(lái)管理bean,能夠基于Restful實(shí)現(xiàn)頁(yè)面請(qǐng)求交互功能
基礎(chǔ)篇:熟練掌握Mybatis
創(chuàng)建第一個(gè)SpringBoot項(xiàng)目
在Spring官方下創(chuàng)建SpringBoot項(xiàng)目
一、打開Spring官方—>projects—>SpringBoot—>Spring initializr;
或者點(diǎn)擊創(chuàng)建SpringBoot看到以下圖片:
按照上述圖片完成后執(zhí)行第7步會(huì)下載一個(gè)壓縮包:
二、找到壓縮包位置解壓
三、導(dǎo)入創(chuàng)建好的SpringBoot項(xiàng)目
打開IEDA:file—>open:找到剛才文件解壓位置,加載進(jìn)來(lái)即可
或者直接把解壓好的文件拖進(jìn)IDEA也可以:
如圖:
使用IDEA創(chuàng)建SpringBoot項(xiàng)目
說(shuō)明:我們一般是不會(huì)在Spring的官網(wǎng)上創(chuàng)建SpringBoot項(xiàng)目的,而是使用IDEA創(chuàng)建項(xiàng)目,因?yàn)镮EDA為我們準(zhǔn)備好了創(chuàng)建工具,這樣的創(chuàng)建更加省時(shí)省力。
一、打開IEDA新建一個(gè)項(xiàng)目,就叫做SpringBoot:
二、在項(xiàng)目里新建一個(gè)modules,取名為SpringBoot-demo1
在上面點(diǎn)擊Next之后,跳到下面圖片
選中之后點(diǎn)擊finish—>apply—>ok即可
三、編寫測(cè)試程序
在Application嘗試輸出一段話,檢查一下代碼系統(tǒng)是否正確:
package com.example.springbootdemo1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootDemo1Application {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemo1Application.class, args);
System.out.println("雞到底美不美?");
}
}
很明顯,我們創(chuàng)建的第一個(gè)SpringBoot成功了。
SpringBoot配置文件詳解
屬性配置
一、 我們可以看到,SpringBoot項(xiàng)目下的Resources目錄下有一個(gè)application.properties的配置文件,SpringBoot通過(guò)配置文件application.properties就可以修改默認(rèn)的配置,什么意思呢?舉個(gè)例子,因?yàn)镾pringBoot采用的是內(nèi)嵌tomcat的方式,所以默認(rèn)端口是8080,我現(xiàn)在通過(guò)application.properties配置文件把8080修改為8081:
server.port=8081
執(zhí)行測(cè)試:可以看到端口號(hào)已經(jīng)由8080變?yōu)?081
上述例子說(shuō)明了application.properties配置文件可以更改SpringBoot提供的默認(rèn)配置,設(shè)置成我們實(shí)際需要的配置。
配置文件分類
SpringBoot使用一個(gè)全局的配置文件,配置文件名是固定的(都必須是application.開頭),支持三種格式(properties、yaml、yml),由于properties類型的我們已經(jīng)用過(guò)很多,這里就不再過(guò)多贅述,這里介紹一下yaml或者yml。
一、創(chuàng)建application.yaml、application.yml文件
yml:
yaml:
可以看到兩者的用法和格式完全一樣,那么是不是說(shuō)兩個(gè)作用一樣呢?答案是兩者一樣,所以在使用過(guò)程中,我們一般選擇yml格式
二、yml、yaml的注意點(diǎn)
1、以空格的縮進(jìn)來(lái)控制層級(jí)關(guān)系,左對(duì)齊的一列數(shù)據(jù),屬于同一個(gè)層級(jí)
2、yaml、yml 格式:k: v,之間的空格必須有
3、k 和 v 對(duì)大小寫敏感
4、k: v,字符串默認(rèn)不用加上單引號(hào)或者雙引號(hào)
5、在這兩個(gè)配置文件中#表示注釋
三、yml中各種數(shù)據(jù)類型的使用
對(duì)象、map類:
普通寫法:
Practitioner:
name: kunkun
age: 3
行內(nèi)寫法:
Practitioner: {name: kunkun,age: 3}
數(shù)組:
普通寫法:
#縮略格式
Practitioner:
- name: kunkun
age:3
likes:
- sing
- dance
- rap
- basketball
- name: xiaoheizi
age: 4
likes:
- kunkun
- zhenxiatou
- suzhi666
行內(nèi)寫法:
Practitioner: [{name: kunkun,age: 3,hobby: [sing,dance,rap,basketball]},
{name: xiaoheizi,age: 4,hobby: [kunkun,zhenxiatou,suzhi666]}]
四、配置文件讀取
1、讀取單個(gè)數(shù)據(jù)
package com.example.springbootdemo1.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
/**
* @author 不止于夢(mèng)想
* @date 2022/10/21 21:12
*/
@RestController
public class indexController {
@Value("${name}")
public String username;
@ResponseBody
@RequestMapping("/index")
public String welcomeView(){
ModelAndView mv = new ModelAndView();
mv.addObject("user",username);
System.out.println(username);
return "hello";
}
}
//配置文件
name: kunkun
結(jié)果:
技巧:如果數(shù)據(jù)存在多層級(jí),依次書寫層級(jí)名稱即可
注意:這里踩一個(gè)坑,我們?cè)趯懪渲梦募臅r(shí)候,一般都是key value鍵值對(duì)的,而key的值除非是你想要的,不然不要寫成user,寫成user系統(tǒng)會(huì)自動(dòng)賦值為你系統(tǒng)的管理員:
#這里嘗試驗(yàn)證
user:
name: kunkun
package com.example.springbootdemo1.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
/**
* @author 不止于夢(mèng)想
* @date 2022/10/21 21:12
*/
@Controller
public class indexController {
@Value("${user.name}")
public String username;
@ResponseBody
@RequestMapping("/index")
public String welcomeView(){
ModelAndView mv = new ModelAndView();
mv.addObject("user",username);
System.out.println(username.toString());
return "hello";
}
}
結(jié)果如下:
2、讀取全部數(shù)據(jù)
提問(wèn):讀取全部數(shù)據(jù)是使用@value標(biāo)簽給所有屬性都注入值?
從上面我們可以看到,如果配置文件里的值是少量的,那么可以用@value標(biāo)簽給需要的屬性賦值,但是在我們的日常開發(fā)中,配置文件的內(nèi)容很多,一個(gè)一個(gè)注入得把我們累死!
解決方案:SpringBoot提供了一個(gè)對(duì)象,能夠把所有的數(shù)據(jù)都封裝到這一個(gè)對(duì)象中,這個(gè)對(duì)象叫做Environment,使用自動(dòng)裝配注解可以將所有的yaml數(shù)據(jù)封裝到這個(gè)對(duì)象中
3、讀取對(duì)象數(shù)據(jù)
因?yàn)镴ava是一個(gè)面向?qū)ο蟮恼Z(yǔ)言,很多情況下,我們會(huì)將一組數(shù)據(jù)封裝成一個(gè)對(duì)象。SpringBoot也提供了可以將一組yml對(duì)象數(shù)據(jù)封裝一個(gè)Java對(duì)象的操作:
第一步:編寫配置文件
student:
username: kunkun
age: 3
hobby: dance
第二步:編寫一個(gè)對(duì)象類,并且將該對(duì)象類作為bean注入到Spring容器中,然后使用注解@ConfigurationProperties指定該對(duì)象加載哪一組yaml中配置的信息。
package com.example.springbootdemo1.pojo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component//交給Spring容器保管
@ConfigurationProperties(prefix = "student")//對(duì)應(yīng)的application.yml配置文件的位置
public class Student{
private String username;
private int age;
private String hobby;
@Override
public String toString() {
return "Student{" +
"username='" + username + '\'' +
", age=" + age +
", hobby='" + hobby + '\'' +
'}';
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public Student() {
}
public Student(String username, int age, String hobby) {
this.username = username;
this.age = age;
this.hobby = hobby;
}
}
第三步,編寫測(cè)試類
package com.example.springbootdemo1;
import com.example.springbootdemo1.pojo.Student;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
class SpringBootDemo1ApplicationTests {
@Autowired
private Student student;
@Test
void contextLoads() {
System.out.println(student);
}
}
測(cè)試結(jié)果如下:
總結(jié):@value和@ConfigurationProperties都是獲取配置文件信息的;@value常用在獲取單個(gè)或者少量的配置文件,而后者常需要對(duì)應(yīng)配置文件屬性的封裝類,即把文件屬性映射寫成一個(gè)封裝的類,并把類交給spring管理(常配合Component使用)。然后使用@ConfigurationProperties添加前綴以對(duì)應(yīng)起來(lái)配置文件的屬性。
SpringBoot整合Thymeleaf模板引擎
Thymeleaf簡(jiǎn)介
一、Thymeleaf是一個(gè)流行的模板引擎,該模板引擎采用Java語(yǔ)言開發(fā),模板引擎是一個(gè)技術(shù)名詞,是跨領(lǐng)域跨平臺(tái)的概念,在Java語(yǔ)言體系下有模板引擎,在C#、PHP語(yǔ)言體系下也有模板引擎。除了thymeleaf之外還有Velocity、FreeMarker等模板引擎,功能類似
二、Thymeleaf的主要目標(biāo)是將優(yōu)雅的自然模板帶到您的開發(fā)工作流程中—HTML能夠在瀏覽器中正確顯示,并且可以作為靜態(tài)原型,從而在開發(fā)團(tuán)隊(duì)中實(shí)現(xiàn)更強(qiáng)大的協(xié)作。Thymeleaf能夠處理HTML,XML,JavaScript,CSS甚至純文本。
三、Thymeleaf的主要目標(biāo)是提供一個(gè)優(yōu)雅和高度可維護(hù)的創(chuàng)建模板的方式。 為了實(shí)現(xiàn)這一點(diǎn),它建立在自然模板的概念之上,以不影響模板作為設(shè)計(jì)原型的方式將其邏輯注入到模板文件中。 這改善了設(shè)計(jì)溝通,彌合了前端設(shè)計(jì)和開發(fā)人員之間的理解偏差。
示例:Thymeleaf 通過(guò)在 html 標(biāo)簽中,增加額外屬性來(lái)達(dá)到“模板+數(shù)據(jù)”的展示方式,示例代碼如下。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"><!--引入thymeleaf命名空間-->
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--th:text 為 Thymeleaf 屬性,用于在展示文本-->
<h1 th:text="歡迎來(lái)到Thymeleaf">歡迎訪問(wèn)靜態(tài)頁(yè)面</h1>
</body>
</html>
當(dāng)直接使用瀏覽器打開時(shí),瀏覽器展示結(jié)果如下。
歡迎來(lái)到Thymeleaf
當(dāng)通過(guò) Web 應(yīng)用程序訪問(wèn)時(shí),瀏覽器展示結(jié)果如下。
歡迎訪問(wèn)靜態(tài)頁(yè)面
整合
SpringBoot整合Thymeleaf需要三個(gè)步驟:
一、引入對(duì)應(yīng)Thymeleaf的starter,其實(shí)在以后的整合中,要整合什么技術(shù),就引入該技術(shù)的starter即可:
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.7.3</version>
</dependency>
二、創(chuàng)建模板文件,并放在指定目錄下
2.1 由于 SpringBoot 為 thymeleaf 提供了一整套的自動(dòng)化配置方案,我們幾乎不用做任何更改就可以直接使用,如下是SpringBoot中thymeleaf的默認(rèn)配置
@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
/**
* Whether to check that the template exists before rendering it.
*/
private boolean checkTemplate = true;
/**
* Whether to check that the templates location exists.
*/
private boolean checkTemplateLocation = true;
/**
* Prefix that gets prepended to view names when building a URL.
*/
private String prefix = DEFAULT_PREFIX;
/**
* Suffix that gets appended to view names when building a URL.
*/
private String suffix = DEFAULT_SUFFIX;
/**
* Template mode to be applied to templates. See also Thymeleaf's TemplateMode enum.
*/
private String mode = "HTML";
...
}
通過(guò) org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties 找到 SpringBoot 中 thymeleaf 的默認(rèn)配置:
@ConfigurationProperties //這個(gè)注解熟不熟悉,這不就是上面的讀取配置文件注入的注解嗎? DEFAULT_ENCODING :默認(rèn)字符編碼,為utf-8 DEFAULT_PREFIX 默認(rèn)前綴表達(dá)式,值為"classpath:/templates/",即類路徑下的templates,對(duì)應(yīng)了SpringBoot項(xiàng)目下的Resource下的templates。 DEFAULT_SUFFIX 后綴表達(dá)式,默認(rèn)為.html
從上面代碼可以看出,thymeleaf 模板文件默認(rèn)放在 resources/templates 目錄下,默認(rèn)的后綴是 .html。
當(dāng)然,我們有時(shí)候不想用默認(rèn)配置,因?yàn)樾枨笫嵌鄻拥?,這個(gè)時(shí)候SpringBoot也是提供了個(gè)性化的方法供我們使用。;
在SpringBoot配置文件中:
spring:
#thymeleaf模板引擎
thymeleaf:
#是否開啟緩存
cache: false
#編碼格式
encoding: UTF-8
這里我把緩存關(guān)閉,就能使頁(yè)面進(jìn)行實(shí)時(shí)的更新。
三、整合thymeleaf 模板引擎
上面已經(jīng)把starter導(dǎo)入了,然后配置了thymeleaf,接下來(lái)編寫測(cè)試
編寫一個(gè)Controller:
package com.example.springbootdemo1.controller;
import com.example.springbootdemo1.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
import java.util.List;
/**
* @author 不止于夢(mèng)想
* @date 2022/10/21 21:12
*/
@RestController
public class indexController {
@RequestMapping("/index")
public ModelAndView indexView(){
ModelAndView mv = new ModelAndView();
List<User> userList = new ArrayList<>();
for(int i=0;i<5;i++){
User user = new User("zhangsan"+i,5+i);
userList.add(user);
}
mv.addObject("user",userList);
mv.setViewName("index");
return mv;
}
}
編寫要跳轉(zhuǎn)的index.html界面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"><!--引入thymeleaf命名空間-->
<head>
<meta charset="UTF-8">
<title>Title</title>74
</head>
<body>
<table border="1">
<tr>
<td>用戶姓名</td>
<td>用戶年齡</td>
</tr>
<tr th:each="item : ${userList}">
<td th:text="${item.userName}"></td>
<td th:text="${item.userAge}"></td>
</tr>
</table>
</body>
</html>
在配置文件中,編寫視圖解析器:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-422156.html
spring:
#thymeleaf模板引擎
thymeleaf:
#是否開啟緩存
cache: false
#編碼格式
encoding: UTF-8
mvc:
view:
prefix: /pages/
suffix: .html
總結(jié)
SpringBoot是一門十分重要的技術(shù),而學(xué)習(xí)這門技術(shù)有一定的門檻,需要我們掌握Spring技術(shù)棧的相關(guān)東西,而Spring Boot對(duì)于后面分布式的服務(wù)又是至關(guān)重要的,SpringCloud是在Spring Boot基礎(chǔ)之上才能加以學(xué)習(xí)的,所以每一個(gè)Java技術(shù)人員,都應(yīng)該學(xué)好SpringBoot。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-422156.html
到了這里,關(guān)于【Springboot】SpringBoot基礎(chǔ)知識(shí)及整合Thymeleaf模板引擎的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!