springboot整合thymeleaf模板引擎(新手必看)

关于Thymeleaf是什么:

1.Thymeleaf是一个流行的模板引擎,该模板引擎采用Java语言开发。除了thymeleaf之外还有Velocity、FreeMarker等模板引擎,功能类似。
2.Thymeleaf在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以thymeleaf的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
3.Thymeleaf开箱即用的特性。它提供标准和spring标准两种方言,可以直在这里插入代码片接套用模板实现JSTL、OGNL表达式效果,避免每天套模板、改jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。

Thymeleaf整合SpringBoot

**1.**第一步我们要在pom文件里添加依赖,引入thymeleaf

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

**2.**第二步我们要去项目属性文件(application.yml)配置thymeleaf

spring:
    thymeleaf:
        mode: HTML5
        encoding: UTF-8
        cache: false
        prefix: classpath:/templates/demo/

**3.**第三步就要去controller新建一个映射来返回url的请求页面。

ppackage com.enlistentype.controller.demo;

import com.enlistentype.model.umodel.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ThymeleafController {
    @GetMapping("/test")
    public String greetingForm(Model model) {
        model.addAttribute("user", new User());
        return "demo1";
    }
}

很简单的几行代码,往前台传一个对象user。
**3.**第三步我们要新建一个thymeleaf模板,注意要放在application.yml配置的路径下,也就是resource的template。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
    <title>Title</title>
</head>
<body>
<form action="#" th:action="@{/authless/subLogin}" th:object="${user}" method="post">
    <input type="text" th:field="*{userId}" />
    <input type="text" th:field="*{password}" />
    <input type="submit" />
</form>

</body>
</html>

也很简单,主要就是一个用来获取登录名和密码的表单,到这里基本算已经完成了,去访问8080/test就会得到一个有登录表单的页面,如果还想继续下一步就要再在一个controller文件去处理登录数据,再通过user对象返回到前台进行渲染。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值