詳解使用Spring Boot開發(fā)Web項目
前面兩篇博客中我們簡單介紹了spring Boot項目的創(chuàng)建、并且也帶小伙伴們來DIY了一個Spring Boot自動配置功能,那么這些東西說到底最終還是要回歸到Web上才能體現(xiàn)出它的更大的價值,so,今天我們就來看一下如何使用Spring Boot來開發(fā)Web項目。當然,如果小伙伴對Spring Boot尚不熟悉的話,可以先參考一下這兩篇博客:
2.初識Spring Boot框架(二)之DIY一個Spring Boot的自動配置
Spring Boot 提供了spring-boot-starter-web來為Web開發(fā)予以支持,spring-boot-starter-web為我們提供了嵌入的Tomcat以及SpringMVC的依賴,用起來很方便。另外,我們這里還要用到模板引擎,我們做web開發(fā)可選的模板引擎還是挺多的,這里我主要使用Thymeleaf作為模板引擎,事實上,Spring Boot提供了大量的模板引擎,包括FreeMarker、Groovy、Thymeleaf、Velocity和Mustache,在 提供的這么多中它推薦使用Thymeleaf。Thymeleaf在使用的過程中通過ThymeleafAutoConfiguration類對集成所需要的Bean進行自動配置,通過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,從這一段源碼中我們可以看到默認的頁面后綴名為.html,前綴為classpath:/templates/,實際上也就是我們需要把html頁面放到resources文件夾下的templates文件夾中。同時我們也看到了要如何修改這個配置,在application.properties文件中以spring.thymeleaf為前綴來配置相關(guān)屬性。
創(chuàng)建Project
注意創(chuàng)建的時候要選擇Thymeleaf作為依賴,這樣創(chuàng)建成功的Project中將自動包含spring-boot-starter-web,如下圖:
創(chuàng)建JavaBean
我一會要從后臺傳遞數(shù)據(jù)給前臺頁面,數(shù)據(jù)的載體就是這個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; } }
后臺數(shù)據(jù)構(gòu)造
在入口類中添加如下代碼,由后臺向前臺頁面返回兩條數(shù)據(jù),一個單個的Person對象,還有一個people對象是一個List集合,集合中放了3個Person對象,到時候我們直接將這兩條數(shù)據(jù)在html頁面上顯示出來,代碼如下:
@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"; }
這里的代碼都很簡單,不必我多說了,就是返回給前臺頁面兩個對象,一個singlePerson,一個people,另外,我們的前臺頁面叫做index.html。
引入相關(guān)的靜態(tài)文件
這里我使用到了Bootstrap和jQuery兩個庫,當然這個并不是必須的,只是為了讓我們顯示的效果更好看一些,靜態(tài)文件我們要放在src/main/resources/static目錄下。
放置之后目錄如下:
前臺展示頁面
剛才小伙伴們都看到了,默認情況下前臺頁面要放在src/main/resources/templates目錄下,so,我們在該目錄下新建文件就叫index.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文件我簡單介紹一下,首先通過xmlns:th="http://www.thymeleaf.org"導入命名空間,在后期時候的時候,由于html本身是靜態(tài)視圖,在使用相關(guān)屬性的時候加上th:前綴可以使之變?yōu)閯討B(tài)視圖。th:href="@{bootstrap/css/bootstrap.min.css}" rel="external nofollow" rel="external nofollow" 表示引用Web靜態(tài)資源。OK,這是head部分。body部分整體上分為了兩大塊,第一塊顯示我那個單獨的Person對象,第二部分顯示List集合中的Person對象。div的樣式這個沒啥好說的,照著Bootstrap的官網(wǎng)寫就行了,th:text="${singlePerson.name}"表示訪問model中singlePerson的name屬性,th:if="${not #lists.isEmpty(people)}"表示判斷model中的people集合是否為空,th:each="person:${people}"表示遍歷people中的元素,這個和Java里的foreach差不多,person表示迭代元素。th:onclick="'getName(\''+${person.name}+'\');'"表示添加點擊事件,點擊事件由JavaScript來處理。th:inline="javascript"這樣添加到的script標簽可以通過[[${singlePerson}]]訪問model中的屬性。
如此之后,我們便可以運行我們自己的項目了,然后在瀏覽器中訪問,結(jié)果如下:
點擊Button也可以在瀏覽器控制臺看到log輸出:
OK,perfect!
Tomcat相關(guān)配置
上面幾乎沒做什么特別的配置,大部分都使用了SpringBoot提供的默認的配置方式。有的時候我們可能需要有一些自定義的配置,比如Tomcat的配置,很簡單,和上上篇博客說的基本一致,有兩種不同的配置方式:
在application.properties中配置
直接在application.properties中進行配置即可,如下:
server.port=8081#配置服務(wù)器端口,默認為8080 server.session-timeout=1000000#用戶回話session過期時間,以秒為單位 server.context-path=/index#配置訪問路徑,默認為/ server.tomcat.uri-encoding=UTF-8#配置Tomcat編碼,默認為UTF-8 server.tomcat.compression=on#Tomcat是否開啟壓縮,默認為關(guā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); } }
自定義類實現(xiàn)
EmbeddedServletContainerCustomizer接口,然后設(shè)置端口、設(shè)置錯誤請求頁面、設(shè)置會話超時時間等,大家注意這里的404頁面放在src/main/resources/static文件夾下,有了這個之后,當我訪問一個不存在的頁面的時候就會跳轉(zhuǎn)到404.html頁面了。
SpringMVC相關(guān)配置
雖然Spring Boot默認的配置很多情況都可以滿足我們的項目需求,可是有的時候我們可能還是會需要更加靈活的SpringMVC配置,這個時候我們只需要自定義類繼承自WebMvcConfigurerAdapter,然后使用@Configuration和@EnableWebMvc注解,這樣我們會完全屏蔽掉Spring Boot的默認配置,但是正常情況下我們可能只是希望在Spring Boot已有默認配置的基礎(chǔ)上再添加一些配置即Spring Boot提供的默認配置和我自定義的配置并存的情況,這個也簡單,只需要去掉@EnableWebMvc注解就行了。如下代碼:
@Configuration //@EnableWebMvc//無需使用該注解,否則會覆蓋掉SpringBoot的默認配置值 public class WebMVCConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/hello").setViewName("/hello"); } }
自定義Favicon
想要自定義favicon很簡單,只需要將自己的favicon.ico文件放置到src/main/resources目錄下即可,重新運行項目,再看瀏覽器左上角圖標就會變了。如下:
本案例下載地址: 本案例GitHub地址
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot配置連接兩個或多個數(shù)據(jù)庫的實現(xiàn)
本文主要介紹了SpringBoot配置連接兩個或多個數(shù)據(jù)庫的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-05-05Java注解機制之Spring自動裝配實現(xiàn)原理詳解
這篇文章主要為大家詳細介紹了Java注解機制之Spring自動裝配實現(xiàn)原理,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10SpringBoot如何根據(jù)用戶系統(tǒng)時區(qū)動態(tài)展示時間
這篇文章主要介紹了SpringBoot如何根據(jù)用戶系統(tǒng)時區(qū)動態(tài)展示時間,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01Springboot通過lucene實現(xiàn)全文檢索詳解流程
Lucene是一個基于Java的全文信息檢索工具包,它不是一個完整的搜索應用程序,而是為你的應用程序提供索引和搜索功能。Lucene 目前是 Apache Jakarta 家族中的一個開源項目,也是目前最為流行的基于 Java 開源全文檢索工具包2022-06-06