衆所周知,springboot簡化了框架整合的相關配置。默認static中放靜態頁面,templates中放動態頁面。
編寫測試代碼
新建兩個頁面分別放到static和templates目錄下。
static/hello.html
1 2 3 4 5 6 7 8 9 10 |
|
templates/hello.html
1 2 3 4 5 6 7 8 9 10 |
|
新建一個controller,內容如下:注意看兩個方法return代碼的區別,動態沒有html後綴
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
注意:此時我們沒有在pom.xml文件中引入thymeleaf的jar包
測試一下:
http://localhost:8080/hello1,動態訪問,404,找不到頁面
http://localhost:8080/hello2,靜態訪問,訪問static目錄下的靜態資源
http://localhost:8080/hello.html,靜態訪問,訪問static目錄下的靜態資源
添加模板引擎
在pom.xml文件中引入thymeleaf的jar包後,再次測試
1 |
|
http://localhost:8080/hello1,動態訪問,訪問templates目錄下的動態資源
http://localhost:8080/hello2,動態訪問,訪問templates目錄下的動態資源
http://localhost:8080/hello.html,靜態訪問,訪問static目錄下的靜態資源
總結:
1)直接訪問http://localhost:8080/hello.html,不管有沒有模板引擎都只訪問static目錄下的html。
2)添加模板引擎後,通過controller跳轉的頁面不管加不加.html後綴都只訪問templates目錄下的html。
原因:
靜態頁面的return默認是跳轉到/static/hello.html,當在pom.xml中引入了thymeleaf組件,動態跳轉會覆蓋默認的靜態跳轉,默認就會跳轉到/templates/hello.html,注意看兩者return代碼也有區別,動態沒有html後綴。
那麼問題來了,如果使用動態頁面時還想跳轉到/static下的靜態頁面該怎麼辦呢?
使用重定向redirect:
注意觀察,當瀏覽器中訪問http://localhost:8080/hello3時,地址欄會自動變爲http://localhost:8080/hello.html