十五、微服务学习笔记-Thymeleaf

一、为什么要使用Thymeleaf

1、spring boot 内嵌的tomcat不支持jar形式运行jsp页面

2、spring boot 推荐Thymeleaf模版引擎,因为Thymeleaf提供了完美的spring mvc支持

spring boot 提供了大量模版引擎:

(1)FreeMaker

(2)Groovy

(3)Mustache

(4)Thymeleaf

(5)Velocity

(6)Beetl (国产)

 

二、模版技术发展过程

JSP 动态技术 -> html 动静分离 -> node.js vue.js react.js angular.js 前后分离

 

三、使用Thymeleaf

1、pom文件增加依赖

注:引入nekohtml是因为html要准守w3c规则,使用nekohtml可以自动补偿缺失元素

复制代码
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.22</version>
        </dependency>
复制代码

2、在application.yml文件中配置

  thymeleaf:
    cache: false #开发时关闭缓存,不然没法看到实时页面
    mode: HTML
    encoding: utf-8
    servlet:
      content-type: text/html

 

3、创建模版页面,

(1)在/resource/template 目录穿件index.html,在文件中输入html5: 按tab键就会出现一个简单的模版页面

(2)在顶部加入下列一句话

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">

(3)新建一个ThymeleafController,并填入以下内容

复制代码
package com.fjact.hellow.spring.demo.controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ThymeleafController {

    @GetMapping("/index")
    public String index(Model model){
        model.addAttribute("name","张三");
        return "index";
    }
}
复制代码

(4)前端页面设置,在index.html中更增加下面一句话

   <span th:text="${name}">李四</span>

(5)通过路径预览页面

 

问题:注解@RestController和@Controller的区别?

回答:@RestController是@ResponseBody和@Controller合在一起的作用,只能返回json,不能返回页面,所以要返回页面只能是用@Controller,如需返回json,则在Controller方法中加入@ResponseBody注解。

posted @   榕树下的回忆  阅读(284)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示