Spring Boot(19)---開發Web應用之Thymeleaf篇
Spring Boot(19)---開發Web應用之Thymeleaf篇
前言
Web開發是我們平時開發中至關重要的,這裡就來介紹一下Spring Boot對Web開發的支援。
正文
Spring Boot提供了spring-boot-starter-web為Web開發予以支援,spring-boot-starter-web為我們提供了嵌入的Tomcat以及Spring MVC的依賴。
專案結構推薦
一個好的專案結構會讓你開發少一些問題,特別是Spring Boot中啟動類要放在root package下面,我的web工程專案結構如下:
- root package結構:
com.dudu
- 應用啟動類
Application.java
置於root package下,這樣使用@ComponentScan註解的時候預設就掃描當前所在類的package - 實體(Entity)置於
com.dudu.domain
包下 - 邏輯層(Service)置於
com.dudu.service
包下 - controller層(web)置於
com.dudu.controller層
包下 - static可以用來存放靜態資源
- templates用來存放預設的模板配置路徑
Spring Web MVC框架介紹
Spring Web MVC框架(通常簡稱為”Spring MVC”)是一個富”模型,檢視,控制器”的web框架。
Spring MVC允許你建立特定的
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
@RestController @RequestMapping(value="/users") public class MyRestController { @RequestMapping(value="/{user}", method=RequestMethod.GET) public User getUser(@PathVariable Long user) { // ... } @RequestMapping(value="/{user}/customers", method=RequestMethod.GET) List<Customer> getUserCustomers(@PathVariable Long user) { // ... } @RequestMapping(value="/{user}", method=RequestMethod.DELETE) public User deleteUser(@PathVariable Long user) { // ... } } |
Spring MVC自動配置
Spring Boot為Spring MVC提供適用於多數應用的自動配置功能。在Spring預設基礎上,自動配置添加了以下特性:
- 引入ContentNegotiatingViewResolver和BeanNameViewResolver beans。
- 對靜態資源的支援,包括對WebJars的支援。
- 自動註冊Converter,GenericConverter,Formatter beans。
- 對HttpMessageConverters的支援。
- 自動註冊MessageCodeResolver。
- 對靜態index.html的支援。
- 對自定義Favicon的支援。
如果想全面控制Spring MVC,你可以新增自己的@Configuration,並使用@EnableWebMvc對其註解。如果想保留Spring Boot MVC的特性,並只是新增其他的MVC配置(攔截器,formatters,檢視控制器等),你可以新增自己的WebMvcConfigurerAdapter型別的@Bean(不使用@EnableWebMvc註解),具體攔截器等配置後續文章會解析。
靜態檔案
預設情況下,Spring Boot從classpath下一個叫/static(/public,/resources或/META-INF/resources)的資料夾或從ServletContext根目錄提供靜態內容。這使用了Spring MVC的ResourceHttpRequestHandler,所以你可以通過新增自己的WebMvcConfigurerAdapter並覆寫addResourceHandlers方法來改變這個行為(載入靜態檔案)。
在一個單獨的web應用中,容器預設的servlet是開啟的,如果Spring決定不處理某些請求,預設的servlet作為一個回退(降級)將從ServletContext根目錄載入內容。大多數時候,這不會發生(除非你修改預設的MVC配置),因為Spring總能夠通過DispatcherServlet處理請求。
此外,上述標準的靜態資源位置有個例外情況是Webjars內容。任何在/webjars/**路徑下的資源都將從jar檔案中提供,只要它們以Webjars的格式打包。
注:如果你的應用將被打包成jar,那就不要使用src/main/webapp資料夾。儘管該資料夾是一個共同的標準,但它僅在打包成war的情況下起作用,並且如果產生一個jar,多數構建工具都會靜悄悄的忽略它
模板引擎
Spring Boot支援多種模版引擎包括:
- FreeMarker
- Groovy
- Thymeleaf(官方推薦)
- Mustache
JSP技術Spring Boot官方是不推薦的,原因有三:
- tomcat只支援war的打包方式,不支援可執行的jar。
- Jetty 巢狀的容器不支援jsp
- Undertow
- 建立自定義error.jsp頁面不會覆蓋錯誤處理的預設檢視,而應該使用自定義錯誤頁面
當你使用上述模板引擎中的任何一個,它們預設的模板配置路徑為:src/main/resources/templates
。當然也可以修改這個路徑,具體如何修改,可在後續各模板引擎的配置屬性中查詢並修改。
Thymeleaf模板引擎
Thymeleaf是一款用於渲染XML/XHTML/HTML5內容的模板引擎。類似JSP,Velocity,FreeMaker等,它也可以輕易的與Spring MVC等Web框架進行整合作為Web應用的模板引擎。與其它模板引擎相比,Thymeleaf最大的特點是能夠直接在瀏覽器中開啟並正確顯示模板頁面,而不需要啟動整個Web應用。它的功能特性如下:
- Spring MVC中@Controller中的方法可以直接返回模板名稱,接下來Thymeleaf模板引擎會自動進行渲染
- 模板中的表示式支援Spring表示式語言(Spring EL)
- 表單支援,併兼容Spring MVC的資料繫結與驗證機制
- 國際化支援
Spring官方也推薦使用Thymeleaf,所以本篇程式碼整合就使用Thymeleaf來整合。
引入依賴
1 2 3 4 |
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> |
如圖所示,spring-boot-starter-thymeleaf會自動包含spring-boot-starter-web,所以我們就不需要單獨引入web依賴了。
編寫controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
@Controller @RequestMapping("/learn") public class LearnResourceController { @RequestMapping("/") public ModelAndView index(){ List<LearnResouce> learnList =new ArrayList<LearnResouce>(); LearnResouce bean =new LearnResouce("官方參考文件","Spring Boot Reference Guide","http://docs.spring.io/spring-boot/docs/1.5.1.RELEASE/reference/htmlsingle/#getting-started-first-application"); learnList.add(bean); bean =new LearnResouce("官方SpriongBoot例子","官方SpriongBoot例子","https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples"); learnList.add(bean); bean =new LearnResouce("龍國學院","Spring Boot 教程系列學習","http://www.roncoo.com/article/detail/125488"); learnList.add(bean); bean =new LearnResouce("嘟嘟MD獨立部落格","Spring Boot乾貨系列 ","http://tengj.top/"); learnList.add(bean); bean =new LearnResouce("後端程式設計嘟","Spring Boot教程和視訊 ","http://www.toutiao.com/m1559096720023553/"); learnList.add(bean); bean =new LearnResouce("程式猿DD","Spring Boot系列","http://www.roncoo.com/article/detail/125488"); learnList.add(bean); bean =new LearnResouce("純潔的微笑","Sping Boot系列文章","http://www.ityouknow.com/spring-boot"); learnList.add(bean); bean =new LearnResouce("CSDN——小當部落格專欄","Sping Boot學習","http://blog.csdn.net/column/details/spring-boot.html"); learnList.add(bean); bean =new LearnResouce("樑桂釗的部落格","Spring Boot 揭祕與實戰","http://blog.csdn.net/column/details/spring-boot.html"); learnList.add(bean); bean =new LearnResouce("林祥纖部落格系列","從零開始學Spring Boot ","http://412887952-qq-com.iteye.com/category/356333"); learnList.add(bean); ModelAndView modelAndView = new ModelAndView("/index"); modelAndView.addObject("learnList", learnList); return modelAndView; } } |
編寫html
引入依賴後就在預設的模板路徑src/main/resources/templates
下編寫模板檔案即可完成。這裡我們新建一個index.html:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>learn Resources</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <div style="text-align: center;margin:0 auto;width: 1000px; "> <h1>學習資源大奉送,愛我就關注嘟嘟公眾號:嘟爺java超神學堂(javaLearn)</h1> <table width="100%" border="1" cellspacing="1" cellpadding="0"> <tr> <td>作者</td> <td>教程名稱</td> <td>地址</td> </tr> <!--/*@thymesVar id="learnList" type=""*/--> <tr th:each="learn : ${learnList}"> <td th:text="${learn.author}">嘟嘟MD</td> <td th:text="${learn.title}">SPringBoot乾貨系列</td> <td><a th:href="${learn.url}" target="_blank">點我</a></td> </tr> </table> </div> </body> </html> |
注:通過xmlns:th=”http://www.thymeleaf.org“ 命令空間,將靜態頁面轉換為動態的檢視,需要進行動態處理的元素將使用“th:”字首。
ok,程式碼都寫好了,讓我們看對比下直接開啟index.html和啟動工程後訪問http://localhost:8080/learn 看到的效果,Thymeleaf做到了不破壞HTML自身內容的資料邏輯分離。
Thymeleaf的預設引數配置
在application.properties中可以配置thymeleaf模板解析器屬性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# THYMELEAF (ThymeleafAutoConfiguration) #開啟模板快取(預設值:true) spring.thymeleaf.cache=true #Check that the template exists before rendering it. spring.thymeleaf.check-template=true #檢查模板位置是否正確(預設值:true) spring.thymeleaf.check-template-location=true #Content-Type的值(預設值:text/html) spring.thymeleaf.content-type=text/html #開啟MVC Thymeleaf檢視解析(預設值:true) spring.thymeleaf.enabled=true #模板編碼 spring.thymeleaf.encoding=UTF-8 #要被排除在解析之外的檢視名稱列表,用逗號分隔 spring.thymeleaf.excluded-view-names= #要運用於模板之上的模板模式。另見StandardTemplate-ModeHandlers(預設值:HTML5) spring.thymeleaf.mode=HTML5 #在構建URL時新增到檢視名稱前的字首(預設值:classpath:/templates/) spring.thymeleaf.prefix=classpath:/templates/ #在構建URL時新增到檢視名稱後的字尾(預設值:.html) spring.thymeleaf.suffix=.html #Thymeleaf模板解析器在解析器鏈中的順序。預設情況下,它排第一位。順序從1開始,只有在定義了額外的TemplateResolver Bean時才需要設定這個屬性。 spring.thymeleaf.template-resolver-order= #可解析的檢視名稱列表,用逗號分隔 spring.thymeleaf.view-names= |
整合一個bootstrap框架給大家
大家可以直接開啟vanilla-cream-css下面的index.html來檢視靜態效果,如下:
動態效果的話可以檢視template.html
這裡把上面的資源例子重新用bootstrap寫了下,效果不錯哦,如下:
總結
本章到此就結束了,下一篇準備介紹下如何整合jsp,畢竟現在絕大多數的企業還是用jsp來作為模板引擎的。