詳解使用Spring Boot開發(fā)Web項(xiàng)目
前面兩篇博客中我們簡(jiǎn)單介紹了spring Boot項(xiàng)目的創(chuàng)建、并且也帶小伙伴們來DIY了一個(gè)Spring Boot自動(dòng)配置功能,那么這些東西說到底最終還是要回歸到Web上才能體現(xiàn)出它的更大的價(jià)值,so,今天我們就來看一下如何使用Spring Boot來開發(fā)Web項(xiàng)目。當(dāng)然,如果小伙伴對(duì)Spring Boot尚不熟悉的話,可以先參考一下這兩篇博客:
2.初識(shí)Spring Boot框架(二)之DIY一個(gè)Spring Boot的自動(dòng)配置
Spring Boot 提供了spring-boot-starter-web來為Web開發(fā)予以支持,spring-boot-starter-web為我們提供了嵌入的Tomcat以及SpringMVC的依賴,用起來很方便。另外,我們這里還要用到模板引擎,我們做web開發(fā)可選的模板引擎還是挺多的,這里我主要使用Thymeleaf作為模板引擎,事實(shí)上,Spring Boot提供了大量的模板引擎,包括FreeMarker、Groovy、Thymeleaf、Velocity和Mustache,在 提供的這么多中它推薦使用Thymeleaf。Thymeleaf在使用的過程中通過ThymeleafAutoConfiguration類對(duì)集成所需要的Bean進(jìn)行自動(dòng)配置,通過ThymeleafProperties來配置Thymeleaf,包括前綴后綴什么的,我們可以查看ThymeleafProperties一段源碼:
@ConfigurationProperties("spring.thymeleaf") public class ThymeleafProperties { private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8"); private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html"); public static final String DEFAULT_PREFIX = "classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html"; private boolean checkTemplate = true; private boolean checkTemplateLocation = true; private String prefix = "classpath:/templates/"; private String suffix = ".html"; private String mode = "HTML5"; ...... ...... ...... }
OK,從這一段源碼中我們可以看到默認(rèn)的頁(yè)面后綴名為.html,前綴為classpath:/templates/,實(shí)際上也就是我們需要把html頁(yè)面放到resources文件夾下的templates文件夾中。同時(shí)我們也看到了要如何修改這個(gè)配置,在application.properties文件中以spring.thymeleaf為前綴來配置相關(guān)屬性。
創(chuàng)建Project
注意創(chuàng)建的時(shí)候要選擇Thymeleaf作為依賴,這樣創(chuàng)建成功的Project中將自動(dòng)包含spring-boot-starter-web,如下圖:
創(chuàng)建JavaBean
我一會(huì)要從后臺(tái)傳遞數(shù)據(jù)給前臺(tái)頁(yè)面,數(shù)據(jù)的載體就是這個(gè)JavaBean,如下:
public class Person { private String name; private Integer age; public Person() { super(); } public Person(String name, Integer age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
后臺(tái)數(shù)據(jù)構(gòu)造
在入口類中添加如下代碼,由后臺(tái)向前臺(tái)頁(yè)面返回兩條數(shù)據(jù),一個(gè)單個(gè)的Person對(duì)象,還有一個(gè)people對(duì)象是一個(gè)List集合,集合中放了3個(gè)Person對(duì)象,到時(shí)候我們直接將這兩條數(shù)據(jù)在html頁(yè)面上顯示出來,代碼如下:
@RequestMapping("/") public String index(Model model) { Person single = new Person("aa", 11); List<Person> people = new ArrayList<>(); Person p1 = new Person("zhangsan", 11); Person p2 = new Person("lisi", 22); Person p3 = new Person("wangwu", 33); people.add(p1); people.add(p2); people.add(p3); model.addAttribute("singlePerson", single); model.addAttribute("people", people); return "index"; }
這里的代碼都很簡(jiǎn)單,不必我多說了,就是返回給前臺(tái)頁(yè)面兩個(gè)對(duì)象,一個(gè)singlePerson,一個(gè)people,另外,我們的前臺(tái)頁(yè)面叫做index.html。
引入相關(guān)的靜態(tài)文件
這里我使用到了Bootstrap和jQuery兩個(gè)庫(kù),當(dāng)然這個(gè)并不是必須的,只是為了讓我們顯示的效果更好看一些,靜態(tài)文件我們要放在src/main/resources/static目錄下。
放置之后目錄如下:
前臺(tái)展示頁(yè)面
剛才小伙伴們都看到了,默認(rèn)情況下前臺(tái)頁(yè)面要放在src/main/resources/templates目錄下,so,我們?cè)谠撃夸浵滦陆ㄎ募徒衖ndex.html,如下:
<html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8" /> <title>Test20</title> <link th:href="@{bootstrap/css/bootstrap.min.css}" rel="external nofollow" rel="external nofollow" rel="stylesheet" /> <link th:href="@{bootstrap/css/bootstrap-theme.min.css}" rel="external nofollow" rel="stylesheet" /> </head> <body> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">訪問Model</h3> </div> <div class="panel-body"> <span th:text="${singlePerson.name}"></span> </div> </div> <div th:if="${not #lists.isEmpty(people)}"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">列表</h3> </div> <div class="panel-body"> <ul class="list-group"> <li class="list-group-item" th:each="person:${people}"> <span th:text="${person.name}"></span> <span th:text="${person.age}"></span> <button class="btn" th:onclick="'getName(\''+${person.name}+'\');'">獲得名字</button> </li> </ul> </div> </div> </div> <script th:src="@{jquery-3.1.1.js}" type="text/javascript"></script> <script th:src="@{bootstrap/js/bootstrap.min.js}" type="text/javascript"></script> <script th:inline="javascript"> var single = [[${singlePerson}]]; console.log(single.name+"/"+single.age); function getName(name) { console.log(name); } </script> </body> </html>
關(guān)于這一段html文件我簡(jiǎn)單介紹一下,首先通過xmlns:th="http://www.thymeleaf.org"導(dǎo)入命名空間,在后期時(shí)候的時(shí)候,由于html本身是靜態(tài)視圖,在使用相關(guān)屬性的時(shí)候加上th:前綴可以使之變?yōu)閯?dòng)態(tài)視圖。th:href="@{bootstrap/css/bootstrap.min.css}" rel="external nofollow" rel="external nofollow" 表示引用Web靜態(tài)資源。OK,這是head部分。body部分整體上分為了兩大塊,第一塊顯示我那個(gè)單獨(dú)的Person對(duì)象,第二部分顯示List集合中的Person對(duì)象。div的樣式這個(gè)沒啥好說的,照著Bootstrap的官網(wǎng)寫就行了,th:text="${singlePerson.name}"表示訪問model中singlePerson的name屬性,th:if="${not #lists.isEmpty(people)}"表示判斷model中的people集合是否為空,th:each="person:${people}"表示遍歷people中的元素,這個(gè)和Java里的foreach差不多,person表示迭代元素。th:onclick="'getName(\''+${person.name}+'\');'"表示添加點(diǎn)擊事件,點(diǎn)擊事件由JavaScript來處理。th:inline="javascript"這樣添加到的script標(biāo)簽可以通過[[${singlePerson}]]訪問model中的屬性。
如此之后,我們便可以運(yùn)行我們自己的項(xiàng)目了,然后在瀏覽器中訪問,結(jié)果如下:
點(diǎn)擊Button也可以在瀏覽器控制臺(tái)看到log輸出:
OK,perfect!
Tomcat相關(guān)配置
上面幾乎沒做什么特別的配置,大部分都使用了SpringBoot提供的默認(rèn)的配置方式。有的時(shí)候我們可能需要有一些自定義的配置,比如Tomcat的配置,很簡(jiǎn)單,和上上篇博客說的基本一致,有兩種不同的配置方式:
在application.properties中配置
直接在application.properties中進(jìn)行配置即可,如下:
server.port=8081#配置服務(wù)器端口,默認(rèn)為8080 server.session-timeout=1000000#用戶回話session過期時(shí)間,以秒為單位 server.context-path=/index#配置訪問路徑,默認(rèn)為/ server.tomcat.uri-encoding=UTF-8#配置Tomcat編碼,默認(rèn)為UTF-8 server.tomcat.compression=on#Tomcat是否開啟壓縮,默認(rèn)為關(guān)閉
在代碼中進(jìn)行配置
@Component public class CustomServletContainer implements EmbeddedServletContainerCustomizer { @Override public void customize(ConfigurableEmbeddedServletContainer container) { container.setPort(8080); container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND,"/404.html")); container.setSessionTimeout(10, TimeUnit.MINUTES); } }
自定義類實(shí)現(xiàn)
EmbeddedServletContainerCustomizer接口,然后設(shè)置端口、設(shè)置錯(cuò)誤請(qǐng)求頁(yè)面、設(shè)置會(huì)話超時(shí)時(shí)間等,大家注意這里的404頁(yè)面放在src/main/resources/static文件夾下,有了這個(gè)之后,當(dāng)我訪問一個(gè)不存在的頁(yè)面的時(shí)候就會(huì)跳轉(zhuǎn)到404.html頁(yè)面了。
SpringMVC相關(guān)配置
雖然Spring Boot默認(rèn)的配置很多情況都可以滿足我們的項(xiàng)目需求,可是有的時(shí)候我們可能還是會(huì)需要更加靈活的SpringMVC配置,這個(gè)時(shí)候我們只需要自定義類繼承自WebMvcConfigurerAdapter,然后使用@Configuration和@EnableWebMvc注解,這樣我們會(huì)完全屏蔽掉Spring Boot的默認(rèn)配置,但是正常情況下我們可能只是希望在Spring Boot已有默認(rèn)配置的基礎(chǔ)上再添加一些配置即Spring Boot提供的默認(rèn)配置和我自定義的配置并存的情況,這個(gè)也簡(jiǎn)單,只需要去掉@EnableWebMvc注解就行了。如下代碼:
@Configuration //@EnableWebMvc//無需使用該注解,否則會(huì)覆蓋掉SpringBoot的默認(rèn)配置值 public class WebMVCConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/hello").setViewName("/hello"); } }
自定義Favicon
想要自定義favicon很簡(jiǎn)單,只需要將自己的favicon.ico文件放置到src/main/resources目錄下即可,重新運(yùn)行項(xiàng)目,再看瀏覽器左上角圖標(biāo)就會(huì)變了。如下:
本案例下載地址: 本案例GitHub地址
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Spring Boot2.x集成JPA快速開發(fā)的示例代碼
- 使用maven開發(fā)springboot項(xiàng)目時(shí)pom.xml常用配置(推薦)
- springboot項(xiàng)目監(jiān)控開發(fā)小用例(實(shí)例分析)
- 解析SpringBoot項(xiàng)目開發(fā)之Gzip壓縮過程
- 使用Spring Boot搭建Java web項(xiàng)目及開發(fā)過程圖文詳解
- 淺談SpringBoot項(xiàng)目如何讓前端開發(fā)提高效率(小技巧)
- Spring Boot + Thymeleaf + Activiti 快速開發(fā)平臺(tái)項(xiàng)目 附源碼
相關(guān)文章
SpringBoot配置連接兩個(gè)或多個(gè)數(shù)據(jù)庫(kù)的實(shí)現(xiàn)
本文主要介紹了SpringBoot配置連接兩個(gè)或多個(gè)數(shù)據(jù)庫(kù)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05Java注解機(jī)制之Spring自動(dòng)裝配實(shí)現(xiàn)原理詳解
這篇文章主要為大家詳細(xì)介紹了Java注解機(jī)制之Spring自動(dòng)裝配實(shí)現(xiàn)原理,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10java 使用線程做的一個(gè)簡(jiǎn)單的ATM存取款實(shí)例代碼
線程 Thread 類,和 Runable 接口 比較兩者的特點(diǎn)和應(yīng)用領(lǐng)域.可以,直接繼承線程Thread類。該方法編寫簡(jiǎn)單,可以直接操作線程,適用于單重繼承情況,因而不能在繼承其他類,下面我們來看一個(gè)實(shí)例2013-08-08SpringBoot如何根據(jù)用戶系統(tǒng)時(shí)區(qū)動(dòng)態(tài)展示時(shí)間
這篇文章主要介紹了SpringBoot如何根據(jù)用戶系統(tǒng)時(shí)區(qū)動(dòng)態(tài)展示時(shí)間,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-01-01Springboot通過lucene實(shí)現(xiàn)全文檢索詳解流程
Lucene是一個(gè)基于Java的全文信息檢索工具包,它不是一個(gè)完整的搜索應(yīng)用程序,而是為你的應(yīng)用程序提供索引和搜索功能。Lucene 目前是 Apache Jakarta 家族中的一個(gè)開源項(xiàng)目,也是目前最為流行的基于 Java 開源全文檢索工具包2022-06-06