1. 程式人生 > >【Spring Boot】初體驗

【Spring Boot】初體驗

我不能停滯不前

前言

  • 心心念唸的Spring Boot初體驗終於要寫了;
  • Spring Boot專案的具體建立過程不再贅述,因為網上有一堆了。。本文主要介紹我在建立過程中的踩坑,還有填坑
  • 各位看官,在讀文過程中,若有建議,請不吝賜教

建立Spring Boot專案的三種方法

不論idea,還是eclipse,建立Spring Boot專案都是基於以上三種方法之一

關於建立Spring Boot專案,網上已有一堆相關資料,不再贅述;
個人覺得這一篇寫的不錯了,各位看官可以戳這裡:Spring Boot【快速入門】

踩坑

坑一:Failed to configure a DataSource

Failed to configure a DataSource
原因
我在建立專案的時候,匯入了資料庫的相關jar包,在建立後,沒有配置資料庫
* 資料庫:MySQL
* ORM框架:MyBatis
選擇SQL相關jar包

application.properties

解決方案
方案一:刪除pom.xml中資料庫jar包的配置
SQL pom.jpg

方案二:在application.properties中配置資料庫

#MySQL資料庫配置
spring.datasource.url=jdbc:mysql://localhost/blog
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource
.password=root

由於只是初體驗,用不到資料庫,所以我採用方案一;

坑二:addViewControllers無法返回頁面

由於我不想在Controller層寫返回頁面的方法,所以決定自定義一個類實現WebMvcConfigurer介面,重寫addViewControllers方法去返回頁面;沒想到踩坑了┑( ̄Д  ̄)┍
自定義類實現WebMvcConfigurer介面

import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author sincH
 */
@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/h/test").setViewName("test"); } }

結果無法返回頁面
addViewControllers無法返回頁面
原因
通過控制檯的日誌輸出,分析出InternalResourceView渲染頁面失敗了
配置Thymeleaf前

那麼深層分析一下,為啥子會失敗呢?通過網上衝浪得知:
templates資料夾下的的頁面要配置了模板引擎才能訪問到;
由此推測一下,因為InternalResourceView無法訪問到頁面,導致渲染失敗,是嗎??

解決方案
既然知道了原因是沒有配置模板引擎,那麼配置模板引擎即可,我選擇Thymeleaf
1. 修改pom.xml

<!--Thymeleaf模板引擎-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!-->Thymeleaf的非嚴格HTML格式包-->
        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.22</version>
        </dependency>
  1. 修改application.properties
#Thymeleaf 配置
spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
#快取設定為false, 這樣修改之後馬上生效,便於除錯;生產環境下可以設定為true
spring.thymeleaf.cache=false

成功解決!!
test頁面

對比配置Thymeleaf前後的控制檯日誌輸出
配置Thymeleaf前
配置Thymeleaf後

發現
配置Thymeleaf後,是用ThymeleafView去渲染頁面,然後就成了,真是。。怎麼說,甚是妙啊

填坑

  • 關於頁面static資料夾與templates資料夾的區別
    • static存放靜態頁面,templates存放動態頁面
    • static下的頁面,不論是前端,還是後端,都可以用xxx.html 可以訪問到(前提是必須在Web應用根目錄下)
      例如:我的Web應用根目錄是/blog,那麼訪問static下的test頁面,就該這麼寫/blog/test.html
      templates下的頁面需要配置了模板引擎才能訪問到
  • 當類上註解@RestController時,該類方法返回值型別不同,則返回結果不同
    當返回值型別是
    • String;返回(json)字串,而不是渲染檢視;
    • ResponseEntity;返回(json)字串
    • ModelAndView;返回頁面

後記

真的 寫篇技術文章真心不容易;不過這樣也挺好;學習知識點後,寫技術文章可以加深記憶。嗯。。挺好的。

參考文章

下篇預告

【Spring Boot】搭建個人部落格 - 需求分析