SpringBoot使用thymeleaf模板

本文介绍如何在SpringBoot项目中使用Thymeleaf模板引擎实现前后端交互,包括配置依赖、设置模板路径及创建Controller类。

SpringBoot开发的WEB项目Contrller如何跳转到前端页面

目前Spring官方已经不推荐使用JSP来开发WEB了,而是推荐使用如下几种模板引擎来开发:

  • Thymeleaf(Spring官方推荐)
  • FreeMarker
  • Velocity
  • Groovy
  • Mustache

据说,最流行的还是FreeMarker和Velocity这两种模板,我们这里用Spring官方推荐的Thymeleaf模板

在创建好SpringBoot项目的基础上,进行如下配置:

  1. 在POM中到Thymeleaf的依赖

    <!--对HTML的依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
  2. 在application.properties中设置模板寻找路径

    # 模板引擎读取路径
    # 是让controller层到templates文件夹寻找xx.html(src/main/resources/templates)
    spring.thymeleaf.prefix=classpath:/templates/
    
  3. 在resource/templates目录下创建html页面,如index.html

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        在SpringBoot项目中使用HTML页面<br>
        获取页面上传过来的参数PPP:<p th:text="${param1}"></p>
    </body>
    </html>
    
  4. 创建Controller类

    @Controller
    //  这里不能是RestController注解,不然会输出index字符串
    public class HelloWorld {        
        @RequestMapping("/toIndexPage")
        public String getHtmlPage(HashMap<String, Object> map){
            map.put("param1", "hello world");
            return "index"; // 这里的字符串对应html的文件名(不包含后缀)
        }       
    }
    
  5. 访问项目

    http://localhost:8080/toIndexPage        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值