假設一個使用了 Thymeleaf 模板引擎的 Spring Boot 項目,可能有一些模版頁面不需要通過控制器加載數據,只需要直接跳轉展示。
過去使用 SpringMVC 時,如果訪問一個頁面,必須要寫相應的 Controller 類。而 SpringBoot 要實現這個需求只需要直接在 MVC 配置中重寫 addViewControllers 方法配置映射關系即可,不需要在寫相應的 Controller 類。
(1)假設在 resource/templates 目錄下有如下兩個 Thymeleaf 模板頁面:index.html 和 login.html
(2)接着我們自定義一個 MVC 配置,並重寫 addViewControllers 方法進行映射關系配置即可。
@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/index").setViewName("index"); registry.addViewController("/login").setViewName("login"); } }
(3)配置完成后,我們使用 /login 和 /index 就可以分別顯示這兩個 html 頁面了。

