前言
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允許你創建特定的@Controller或@RestController beans來處理傳入的HTTP請求。
示例:
@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來整合。
引入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
如圖所示,spring-boot-starter-thymeleaf會自動包含spring-boot-starter-web,所以我們就不需要單獨引入web依賴了。
編寫controller
@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:
<!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模板解析器屬性
# 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寫了下,效果不錯哦,如下:
![_QV7]N{4}VUV7LRZW_35A`5.png](http://upload-images.jianshu.io/upload_images/1637925-d90351fe3c70b5fa.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
總結
本章到此就結束了,下一篇準備介紹下如何整合jsp,畢竟現在絕大多數的企業還是用jsp來作為模板引擎的。
想要查看更多Spring Boot干貨教程,可前往:Spring Boot干貨系列總綱
源碼下載
( ̄︶ ̄)↗[相關示例完整代碼]
一直覺得自己寫的不是技術,而是情懷,一篇篇文章是自己這一路走來的痕跡。靠專業技能的成功是最具可復制性的,希望我的這條路能讓你少走彎路,希望我能幫你抹去知識的蒙塵,希望我能幫你理清知識的脈絡,希望未來技術之巔上有你也有我,希望大爺你看完打賞點零花錢給我。