thymeleaf 数据_「Java」 - SpringBoot & 接入Thymeleaf

一、概念

模板引擎是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档。

Thymeleaf是一款用于渲染XML/XHTML/HTML 5内容的模板引擎。

类似JSP、Velocity、FreeMaker等,可以简单的与Spring MVC等web框架进行集成作为web应用的模板引擎。与其他模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个web 应用,Spring Boot推荐使用Thymeleaf替代JSP,Spring Boot 2.0中默认使用Thymeleaf 3.0版本作为模板引擎。

A、Thymeleaf特点

  • Thymeleaf在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。因为由于它支持html原型,然后在html标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释html时会忽略未定义的标签属性,所以Thymeleaf的模板可以静态地运行;当有数据返回到页面时,Thymeleaf标签会动态地替换掉静态内容,使页面动态显示。
  • Thymeleaf开箱即用,它提供标准和Spring标准两种方言,可以直接套用模板实现JSTL、OGNL表达式效果,避免套模板、改jstl、改标签的困扰。
  • Thymeleaf提供Spring标准方言和一个与SpringMVC完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

B、对比

Thymeleaf 的模板语法并不会破坏文档的结构,模板依旧是有效的XML文档。模板还可以用作工作原型,Thymeleaf会在运行期替换掉静态值。Velocity与FreeMarker则是连续的文本处理器。

下面的代码示例分别使用Velocity、FreeMarker与Thymeleaf打印出一条消息:

Velocity: <p>$message</p>
FreeMarker: <p>${message}</p>
Thymeleaf: <p th:text="${message}">Hello World!</p>

但是因为Thymeleaf使用了XML DOM解析器,因此它并不适合于处理大规模的XML文件。

二、配置

A、引入Maven配置

<properties>
    <!-- thymeleaf覆盖parent版本 -->
    <thymeleaf.version>3.0.3.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
    <thymeleaf-extras-springsecurity4.version>3.0.2.RELEASE</thymeleaf-extras-springsecurity4.version>
</properties>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>${thymeleaf.version}</version>
</dependency>
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring4</artifactId>
    <version>3.0.2.RELEASE</version>
</dependency>

B、添加SpringBoot配置

# 默认为HTML5模式
spring.thymeleaf.mode=HTML

# 不使用会报网页模板寻找不到异常
spring.thymeleaf.prefix=classpath:/templates/

# 默认使用html后缀
spring.thymeleaf.suffix=.html

# 测试环境,关闭缓存
spring.thymeleaf.cache=false

C、进行相关Bean配置

@Configuration
public class WebMvcConfig implements WebMvcConfigurer, ApplicationContextAware
{
    @Value("${spring.thymeleaf.cache}")
    private boolean thymeleafCacheEnable = true;
    
    private ApplicationContext applicationContext;
    
    /**
     * 获取Spring上下文applicationContext
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
    {
        this.applicationContext = applicationContext;
    }
    
    /**
     * 模板资源解析器
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.thymeleaf")
    public SpringResourceTemplateResolver templateResolver()
    {
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setApplicationContext(this.applicationContext);
        templateResolver.setCharacterEncoding("UTF-8");
        templateResolver.setCacheable(thymeleafCacheEnable);
        return templateResolver;
    }
    
    /**
     * Thymeleaf标准方言解释器
     */
    @Bean
    public SpringTemplateEngine templateEngine()
    {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        // 支持Spring EL表达式
        templateEngine.setEnableSpringELCompiler(true);
        // 支持SpringSecurity方言
        //SpringSecurityDialect securityDialect = new SpringSecurityDialect();
        //templateEngine.addDialect(securityDialect);
        return templateEngine;
    }
    
    /**
     * 视图解析器
     */
    @Bean
    public ThymeleafViewResolver viewResolver()
    {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine());
        return viewResolver;
    }
    
    /**
     * 静态资源加载配置
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
}

三、编写Controller和前端页面

A、Controller

@Slf4j
@Controller
public class HomeController
{
    @LogBack
    @GetMapping("/")
    public String index(Model model)
    {
        model.addAttribute("name", "isisiwish");
        log.info("index");
        return "index";
    }
}

B、HTML模板

页面模板默认放在srcmainresourcestemplatesindex.html目录下,使用@Controller注解,返回模板名称即可。所有使用Thymeleaf的页面必须在HTML标签声明Thymeleaf。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Search House</title>
    <link href="/static/css/bootstrap.css" rel="stylesheet" type="text/css"/>
    <link href="/static/css/common.css" rel='stylesheet' type='text/css'/>
</head>
<body>
    <h2>Search House Index</h2>
    <h4 th:text="${name}"></h4>
</body>
</html>

1b17e27b3426a2c1173636158c6c09d8.png
[20:24:48.365] [t.c.searchhouse.util.aop.LogAspect-http-nio-8080-exec-1:31] [INFO] - before
[20:24:48.375] [t.c.searchhouse.web.HomeController-http-nio-8080-exec-1:25] [INFO] - index
[20:24:48.376] [t.c.searchhouse.util.aop.LogAspect-http-nio-8080-exec-1:37] [INFO] - after

成功接入Thymeleaf模板引擎。

四、中文乱码问题

A、设置HTML编码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>403 Forbidden</title>
</head>
<body>
<h1>Access Denied</h1>
<h2>无权访问该页面</h2>
<a href="/">返回首页</a>
</body>
</html>

B、修改Config,设置字符编码为UTF-8

/**
 * 模板资源解析器
 */
@Bean
@ConfigurationProperties(prefix = "spring.thymeleaf")
public SpringResourceTemplateResolver templateResolver()
{
    SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
    templateResolver.setApplicationContext(this.applicationContext);
    templateResolver.setCharacterEncoding("UTF-8");
    templateResolver.setCacheable(thymeleafCacheEnable);
    return templateResolver;
}
    
/**
 * 视图解析器
 */
@Bean
public ThymeleafViewResolver viewResolver()
{
    ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
    viewResolver.setTemplateEngine(templateEngine());
    viewResolver.setCharacterEncoding("UTF-8");
    return viewResolver;
}

Thymeleaf是一个非常灵活和优秀的前端页面模板引擎,使用Thymeleaf可以非常灵活的对页面进行布局,复用通用页面。Thymeleaf提供了各种常用的语法,非常方便在前端页面中使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值