1. 出錯現象
我們知道 Thymeleaf 模板引擎規定的文件路勁應該是在 templates 目錄下面的。
但是筆者在開發的過程中,滿足了上述要求但是還是沒能映射成功。
我們來看看 index.html 裏面有什麼東西
在來看看訪問 localhost:8080/index 時打開的網頁是什麼樣子的:
它這裏是直接顯示了字符串 index,而不是進行模板引擎的解析。說明此處出現了錯誤。
2. 解決方案
首先看看有沒有導入 Thymeleaf 的依賴座標
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
筆者之前就導入了,所以這個不是出錯的原因。
最後經測試,發現是 @RestController 惹的禍。其原因是:但是如果使用@RestController註解,視圖解析器InternalResourceViewResolver會失效,無法解析html、jsp頁面進而跳轉到指定的頁面,而是返回return的內容。
因此解決方法就是將 @RestController 改成 @Controller
再次訪問 localhost:8080/index
發現解析成功,這樣問題就解決了。
3. 反思提升
但是我們爲了編碼的方便,我們一般都會用 @RestController 來替代 @Controller + @ResponseBody。
所以如果我們一定要用 @RestController 註解的話,該如何實現頁面的跳轉呢?
剛剛提到使用 @RestController 註解的話,視圖解析器會失效,如果返回值是 String 的話,那麼就只會返回 String 的內容。所以這裏肯定不能返回 String。
經筆者學習研究,發現可以用以下方法實現頁面的跳轉:
@RestController
public class IndexController {
@GetMapping("/index")
public ModelAndView index(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index");
return modelAndView;
}
}
我們改用返回一個 ModelAndView 對象,這樣就可以實現頁面跳轉了。
運行後重新訪問路徑,結果是一樣的。