SpringBoot - 路径映射(实现不通过Controller直接访问模版页面)

本文介绍了如何在 SpringBoot 项目中,使用 Thymeleaf 模板引擎,无需编写对应 Controller 直接通过 MVC 配置映射页面。通过重写 `addViewControllers` 方法,可以将 `/index` 和 `/login` 映射到对应的模板页面,实现静态页面的直接展示。
摘要由CSDN通过智能技术生成

叙述

假设一个使用了 Thymeleaf 模板引擎的 Spring Boot 项目,可能有一些模版页面不需要通过控制器加载数据,只需要直接跳转展示。

    过去使用 SpringMVC 时,如果访问一个页面,必须要写相应的 Controller 类。而 SpringBoot 要实现这个需求只需要直接在 MVC 配置中重写 addViewControllers 方法配置映射关系即可,不需要在写相应的 Controller 类。

解决方案

(1)假设在 resource/templates 目录下有如下两个 Thymeleaf 模板页面:index.html 和 login.html

原文:SpringBoot - 路径映射(实现不通过Controller直接访问模版页面)

(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 页面了

原文:SpringBoot - 路径映射(实现不通过Controller直接访问模版页面)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Spring Boot框架时,我们可以使用Thymeleaf模板引擎来渲染HTML页面Thymeleaf是一种面向服务器的模板引擎,它可以用来构建与Web标准兼容的HTML5页面。 在Spring Boot中,我们首先需要在pom.xml文件中添加Thymeleaf依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` 在Spring Boot应用程序中,我们需要配置Thymeleaf的视图解析器。可以在application.properties文件中添加以下属性: ``` spring.thymeleaf.enabled=true spring.thymeleaf.cache=false ``` 可以看到,我们打开了Thymeleaf的缓存机制,以便更方便地测试HTML页面的更改。然后,我们需要在我们的Spring Boot应用程序中创建一个控制器,以便为HTML页面提供服务: ``` @Controller public class MyController { @GetMapping("/") public String index(Model model) { model.addAttribute("message", "Hello, Thymeleaf!"); return "index"; } } ``` 在上面的控制器中,我们使用@GetMapping注释来将应用程序映射到“/”路径。然后,我们将一个消息添加到Model中,以便将其传递给Thymeleaf视图。最后,我们返回视图名称“index”,这将是我们要渲染的HTML页面。 在Thymeleaf模板中,我们可以使用th:text属性来将消息添加到HTML页面中: ``` <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Hello, Thymeleaf</title> </head> <body> <h1 th:text="${message}">Hello, World!</h1> </body> </html> ``` 在上面的示例中,我们使用th:text属性来向页面添加消息。可以看到,我们使用了Thymeleaf的EL表达式来获取控制器中传递的消息。 使用了这些步骤后,当我们访问应用程序的根目录时,会渲染index.html页面,并将消息“Hello, Thymeleaf!”添加到页面中。这就是如何在Spring Boot应用程序中使用Thymeleaf模板引擎来渲染HTML页面
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值