1.什么是thymeleaf

Thymeleaf是一种现代的服务器侧Java模版引擎,既能用于网络,也能用于独立的环境。它能够处理HTML,XML,JavaScript,CSS,甚至纯文本。

Thymeleaf的主要目标是为创建模版提供一种优雅、高️维护性的方法。为了实现这个目标,它建立在自然模版的观念之上。也就是以某种方式将它的逻辑注入模版文件之中,而不会影响模版作为一个设计原型被使用。这改善了设计上的交流,同时也在设计和开发团队之间架起了一座桥梁。

Thymeleaf的特点

  • Thymeleaf具有可读性强、易于理解的语法。
  • Thymeleaf支持Spring MVC的所有特性,可以与Spring框架无缝集成。
  • Thymeleaf可以在没有Web服务器的情况下运行,便于开发和测试。
  • Thymeleaf支持多种模板解析器,可以根据需要选择合适的解析器。

Thymeleaf的应用场景

Thymeleaf 是一款适用于各种 Web 应用程序的强大模板引擎,无论是传统的服务器端 Web 应用程序、单页应用程序,还是移动 Web 应用程序,都能够轻松应对。此外,Thymeleaf 不仅局限于动态内容的生成,还可以用于生成静态内容,如电子邮件模板等,为开发者提供了极大的便利和灵活性。

2.代码工程

实验目的:用Thymeleaf作为模版输出页面html

pom.xml



    
        springboot-demo
        com.et
        1.0-SNAPSHOT
    
    4.0.0

    thymeleaf

    
        8
        8
    
    

        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-autoconfigure
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.projectlombok
            lombok
        

    

controller

package com.et.thymeleaf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

@Controller
public class HelloWorldController {
    @RequestMapping("/")
    public String index()
    {
        return"index";
    }
    @RequestMapping(value="/save", method= RequestMethod.POST)
    public ModelAndView save(@ModelAttribute User user)
    {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("result");
        modelAndView.addObject("user", user);
        return modelAndView;
    }
}

entity

package com.et.thymeleaf.controller;

import lombok.Data;

/**
 * @author liuhaihua
 * @version 1.0
 * @ClassName User
 * @Description todo
 * @date 2024年06月03日 10:48
 */
@Data
public class User {
    private String name;
    private int  age;
    private String email;

}

application.properties

spring.thymeleaf.cache=false
spring.thymeleaf.suffix: .html

index.html



    Index Page



    

result.html


User Name:

Email ID:

以上只是一些关键代码,所有代码请参见下面代码仓库

代码仓库

  • GitHub – Harries/springboot-demo: a simple springboot demo with some components for example: redis,solr,rockmq and so on.

3.测试

启动Spring Boot应用

测试模版

  • 访问http://127.0.0.1:8080/ 输入参数,
  • 点击提交自动跳转到http://127.0.0.1:8080/save,并且展示前一个页面输入的参数

4.引用

  • Thymeleaf
本站无任何商业行为
个人在线分享 » Spring Boot集成thymeleaf快速入门demo
E-->