javascript
使用Spring Boot开发Web项目
前面兩篇博客中我們簡單介紹了spring?Boot項目的創建、并且也帶小伙伴們來DIY了一個Spring Boot自動配置功能,那么這些東西說到底最終還是要回歸到Web上才能體現出它的更大的價值,so,今天我們就來看一下如何使用Spring Boot來開發Web項目。當然,如果小伙伴對Spring Boot尚不熟悉的話,可以先參考一下這兩篇博客:
1.初識Spring Boot框架
2.初識Spring Boot框架(二)之DIY一個Spring Boot的自動配置
Spring Boot 提供了spring-boot-starter-web來為Web開發予以支持,spring-boot-starter-web為我們提供了嵌入的Tomcat以及SpringMVC的依賴,用起來很方便。另外,我們這里還要用到模板引擎,我們做web開發可選的模板引擎還是挺多的,這里我主要使用Thymeleaf作為模板引擎,事實上,Spring Boot提供了大量的模板引擎,包括FreeMarker、Groovy、Thymeleaf、Velocity和Mustache,在 提供的這么多中它推薦使用Thymeleaf。Thymeleaf在使用的過程中通過ThymeleafAutoConfiguration類對集成所需要的Bean進行自動配置,通過ThymeleafProperties來配置Thymeleaf,包括前綴后綴什么的,我們可以查看ThymeleafProperties一段源碼:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | @ConfigurationProperties("spring.thymeleaf") publicclass ThymeleafProperties { ????privatestatic final Charset DEFAULT_ENCODING = Charset.forName("UTF-8"); ????privatestatic final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html"); ????publicstatic final String DEFAULT_PREFIX = "classpath:/templates/"; ????publicstatic final String DEFAULT_SUFFIX = ".html"; ????privateboolean checkTemplate = true; ????privateboolean checkTemplateLocation = true; ????privateString prefix = "classpath:/templates/"; ????privateString suffix = ".html"; ????privateString mode = "HTML5"; ????...... ????...... ????...... } |
OK,從這一段源碼中我們可以看到默認的頁面后綴名為.html,前綴為classpath:/templates/,實際上也就是我們需要把html頁面放到resources文件夾下的templates文件夾中。同時我們也看到了要如何修改這個配置,在application.properties文件中以spring.thymeleaf為前綴來配置相關屬性。
關于Thymeleaf如果小伙伴們還不太了解可以先看看我在網上找到的這個資料Thymeleaf中文文檔最新版。OK,這些算是準備工作了。接下來我們就從項目的創建開始看起吧。
創建Project
注意創建的時候要選擇Thymeleaf作為依賴,這樣創建成功的Project中將自動包含spring-boot-starter-web,如下圖:
創建JavaBean
我一會要從后臺傳遞數據給前臺頁面,數據的載體就是這個JavaBean,如下:
| 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 | publicclass Person { ????privateString name; ????privateInteger age; ????publicPerson() { ????????super(); ????} ????publicPerson(String name, Integer age) { ????????super(); ????????this.name = name; ????????this.age = age; ????} ????publicString getName() { ????????returnname; ????} ????publicvoid setName(String name) { ????????this.name = name; ????} ????publicInteger getAge() { ????????returnage; ????} ????publicvoid setAge(Integer age) { ????????this.age = age; ????} } |
后臺數據構造
在入口類中添加如下代碼,由后臺向前臺頁面返回兩條數據,一個單個的Person對象,還有一個people對象是一個List集合,集合中放了3個Person對象,到時候我們直接將這兩條數據在html頁面上顯示出來,代碼如下:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | @RequestMapping("/") ????publicString index(Model model) { ????????Person single = newPerson("aa",11); ????????List<Person> people = newArrayList<>(); ????????Person p1 = newPerson("zhangsan",11); ????????Person p2 = newPerson("lisi",22); ????????Person p3 = newPerson("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。
引入相關的靜態文件
這里我使用到了Bootstrap和jQuery兩個庫,當然這個并不是必須的,只是為了讓我們顯示的效果更好看一些,靜態文件我們要放在src/main/resources/static目錄下。
1.Bootstrap下載
2.jQuery下載
放置之后目錄如下:
前臺展示頁面
剛才小伙伴們都看到了,默認情況下前臺頁面要放在src/main/resources/templates目錄下,so,我們在該目錄下新建文件就叫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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | <htmllang="en"xmlns:th="http://www.thymeleaf.org"> <head> ????<metacharset="UTF-8"/> ????<title>Test20</title> ????<linkth:href="@{bootstrap/css/bootstrap.min.css}"rel="stylesheet"/> ????<linkth:href="@{bootstrap/css/bootstrap-theme.min.css}"rel="stylesheet"/> </head> <body> <divclass="panel panel-primary"> ????<divclass="panel-heading"> ????????<h3class="panel-title">訪問Model</h3> ????</div> ????<divclass="panel-body"> ????????<spanth:text="${singlePerson.name}"></span> ????</div> </div> <divth:if="${not #lists.isEmpty(people)}"> ????<divclass="panel panel-primary"> ????????<divclass="panel-heading"> ????????????<h3class="panel-title">列表</h3> ????????</div> ????????<divclass="panel-body"> ????????????<ulclass="list-group"> ????????????????<liclass="list-group-item"th:each="person:${people}"> ????????????????????<spanth:text="${person.name}"></span> ????????????????????<spanth:text="${person.age}"></span> ????????????????????<buttonclass="btn"th:onclick="'getName(\''+${person.name}+'\');'">獲得名字</button> ????????????????</li> ????????????</ul> ????????</div> ????</div> </div> <scriptth:src="@{jquery-3.1.1.js}"type="text/javascript"></script> <scriptth:src="@{bootstrap/js/bootstrap.min.js}"type="text/javascript"></script> <scriptth:inline="javascript"> ????var single = [[${singlePerson}]]; ????console.log(single.name+"/"+single.age); ????function getName(name) { ????????console.log(name); ????} </script> </body> </html> |
關于這一段html文件我簡單介紹一下,首先通過xmlns:th="http://www.thymeleaf.org"導入命名空間,在后期時候的時候,由于html本身是靜態視圖,在使用相關屬性的時候加上th:前綴可以使之變為動態視圖。th:href="@{bootstrap/css/bootstrap.min.css}"表示引用Web靜態資源。OK,這是head部分。body部分整體上分為了兩大塊,第一塊顯示我那個單獨的Person對象,第二部分顯示List集合中的Person對象。div的樣式這個沒啥好說的,照著Bootstrap的官網寫就行了,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中的屬性。
如此之后,我們便可以運行我們自己的項目了,然后在瀏覽器中訪問,結果如下:
點擊Button也可以在瀏覽器控制臺看到log輸出:
OK,perfect!
Tomcat相關配置
上面幾乎沒做什么特別的配置,大部分都使用了SpringBoot提供的默認的配置方式。有的時候我們可能需要有一些自定義的配置,比如Tomcat的配置,很簡單,和上上篇博客說的基本一致,有兩種不同的配置方式:
在application.properties中配置
直接在application.properties中進行配置即可,如下:
| 1 2 3 4 5 | server.port=8081#配置服務器端口,默認為8080 server.session-timeout=1000000#用戶回話session過期時間,以秒為單位 server.context-path=/index#配置訪問路徑,默認為/ server.tomcat.uri-encoding=UTF-8#配置Tomcat編碼,默認為UTF-8 server.tomcat.compression=on#Tomcat是否開啟壓縮,默認為關閉 |
在代碼中進行配置
| 1 2 3 4 5 6 7 8 9 | @Component publicclass CustomServletContainer implementsEmbeddedServletContainerCustomizer { ????@Override ????publicvoid customize(ConfigurableEmbeddedServletContainer container) { ????????container.setPort(8080); ????????container.addErrorPages(newErrorPage(HttpStatus.NOT_FOUND,"/404.html")); ????????container.setSessionTimeout(10, TimeUnit.MINUTES); ????} } |
自定義類實現
EmbeddedServletContainerCustomizer接口,然后設置端口、設置錯誤請求頁面、設置會話超時時間等,大家注意這里的404頁面放在src/main/resources/static文件夾下,有了這個之后,當我訪問一個不存在的頁面的時候就會跳轉到404.html頁面了。
SpringMVC相關配置
雖然Spring Boot默認的配置很多情況都可以滿足我們的項目需求,可是有的時候我們可能還是會需要更加靈活的SpringMVC配置,這個時候我們只需要自定義類繼承自WebMvcConfigurerAdapter,然后使用@Configuration和@EnableWebMvc注解,這樣我們會完全屏蔽掉Spring Boot的默認配置,但是正常情況下我們可能只是希望在Spring Boot已有默認配置的基礎上再添加一些配置即Spring Boot提供的默認配置和我自定義的配置并存的情況,這個也簡單,只需要去掉@EnableWebMvc注解就行了。如下代碼:
| 1 2 3 4 5 6 7 8 9 | @Configuration //@EnableWebMvc//無需使用該注解,否則會覆蓋掉SpringBoot的默認配置值 publicclass WebMVCConfig extendsWebMvcConfigurerAdapter { ????@Override ????publicvoid addViewControllers(ViewControllerRegistry registry) { ????????registry.addViewController("/hello").setViewName("/hello"); ????} } |
至于這個類里邊的其他方法我就不再贅述了,有興趣的小伙伴可以查看我們之前的文章SpringMVC常用配置。
本案例下載地址:
本案例GitHub地址
以上。
參考資料:
《JavaEE開發的顛覆者 Spring Boot實戰》第七章
原文出處:?sang
from:?http://www.importnew.com/22854.html
總結
以上是生活随笔為你收集整理的使用Spring Boot开发Web项目的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring8:一些常用的Spring
- 下一篇: 什么是Java对象分配率?