SpringBoot - 路徑映射(實現不通過Controller直接訪問模版頁面)


假設一個使用了 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 頁面了。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM