最近在做項目的過程中需要在springboot中跳轉html頁面,參考網上的帖子最後總算是實現了,但是發現在整合的過程中存在很多易犯錯誤,特此記錄一下。
1.pom中引入thymeleaf依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.添加thymeleaf配置
有兩種方式:一種時在application.properties文件中配置,一種是在application.yaml配置文件中配置。
spring:
# thymeleaf頁面模板配置
thymeleaf:
prefix: classpath:/templates/
suffix: .html
prefix配置的是視圖模板的位置,我試着不放在templates下面發現總是報錯,不知道是否可以通過其他配置改成別的路徑。
易犯錯誤配置
spring:
mvc:
view:
suffix: .ftl
prefix: classpath:/templates/
因爲使用了thymeleaf所以,使用mvc的自然是無用的,必須要修改爲thymeleaf才行
3.html模板
作爲thymeleaf模板的html頁面中的元素標籤必須是閉合的,否則會報錯。比如
<meta charset="utf-8">
<base href="/">
<title>thymeleaf</title>
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1"></meta>
<link rel="stylesheet" href="/css/swiper.min.css">
其中“meta、base、link標籤就沒有閉合,啓動時候就會報錯。
需要在html標籤中加入xmlns:th=“http://www.thymeleaf.org”
<html id="ng-app" ng-app="app"
xmlns:th="http://www.thymeleaf.org">
4.controller註解
我剛開始配置的時候,按照例子寫方法怎麼都不能跳頁面,後來發現是controller層中的註解是@Restcontroller而不是@Controller,這樣導致及時在方法上返回的是string類型的,最後還是不能跳頁面。比如:
錯誤形式
~~@RestController~~
@RequestMapping("user")
public class UserController {
@RequestMapping("toIndex")
public String toIndex(){
return "idx/index";
}
}
@RestController註解相當於@Controller註解和@ResponseBody註解,所有不會跳轉頁面,需要改成下面的形式。
@Controller
@RequestMapping("user")
public class UserController {
@RequestMapping("toIndex")
public String toIndex(){
return "idx/index";
}
}
5.總結
目前測試通過上面的配置就可以正常的跳轉到html頁面了,終於不用再使用jsp頁面了。
參考資料
https://blog.csdn.net/sicily_winner/article/details/78985187
https://blog.csdn.net/qq_16307345/article/details/78038224?locationNum=10&fps=1