前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring Boot 集成Thymeleaf

Spring Boot 集成Thymeleaf

原创
作者头像
HLee
修改2021-08-30 18:07:17
2.1K0
修改2021-08-30 18:07:17
举报
文章被收录于专栏:房东的猫房东的猫

简介

Thymeleaf官网 英 [taim li:f] 美 [taɪm lif]

thymeleaf默认的模板存放目录是templates,默认的后缀是html

数据回显

thymeleaf 语法——input、select、radio、textarea 回显

input回填

代码语言:javascript
复制
<div class="form-group">
    <label class="col-sm-1 control-label">用户名:</label>
    <div class="col-sm-3">
        <input id="username" name="username" th:value="${user.username}" class="form-control" type="text">
    </div>  
</div>

单选回填

代码语言:javascript
复制
<div class="form-group">
    <label class="col-sm-1 col-sm-offset-2 control-label">性别 :</label>
    <div class="col-sm-3">
        <label class="radio-inline" th:each="sex:${sexList}">
            <input type="radio" id="sex" name="sex" th:value="${sex.value}" th:text="${sex.name}" th:attr="checked=${user.sex == sex.value?true:false}" />
        </label>
    </div>
</div>

<label for="isDel" class="col-sm-4 control-label">是否删除</label>
<div id="isDel" class="col-sm-8">
    <div class="radio-inline">
        <label><input type="radio" name="isDel"  value="1"  th:field="*{user.isDel}"/>已删除</label>
    </div>
    <div class="radio-inline">
        <label><input type="radio" name="isDel"  value="0"  th:field="*{user.isDel}"/>正常</label>
    </div>
</div>
说明:{ } 中不得出现空格,如 { book.cId}、 {book.cId }、 { book.cId },将报模板解析错误 

时间框回填

代码语言:javascript
复制
<div class="form-group">
    <label class="col-sm-1 control-label">出生日期:</label>
    <div class="col-sm-3">
        <input type="text" class="laydate-icon layer-date form-control" id="birthday" name="birthday" th:value="${user.birthday}==null?null:${#dates.format(user.birthday,'yyyy-MM-dd')}" οnclick="laydate({istime: true, format: 'YYYY-MM-DD'})" style="background-color: #fff;" readonly="readonly" />
    </div>
</div>

下拉回填

代码语言:javascript
复制
<div class="form-group">
    <label class="col-sm-1 col-sm-offset-2 control-label">职业:</label>
    <div class="col-sm-3">
        <select data-placeholder="--选择类别--" name="profession" id="profession" class="form-control chosen-select" tabindex="2" required>
            <option value="">--选择类别--</option>
            <option th:selected="${user.profession eq profession.value}" th:each="profession:${professionTypeList}" th:value="${profession.value}" th:text="${profession.name}"></option>
        </select>
    </div>
</div>

<label  class="col-sm-4 control-label">类别</label>
<div class="col-sm-8">
    <select  id="cId" name="cId"  class="form-control1" >
        <option value="1" th:field="*{book.cId}">目录1</option>
        <option value="2" th:field="*{book.cId}">目录2</option>
        <option value="3" th:field="*{book.cId}">目录3</option>
        <option value="4" th:field="*{book.cId}">目录4</option>
    </select>
</div>
说明:{ } 中,变量名前后不得出现空格,如 { book.cId}、 {book.cId }、 { book.cId },将抛出模板解析错误 

textarea数据回显

代码语言:javascript
复制
内容: <textarea  id="content" name="content" th:text="${user.content}"></textarea>
使用 th:value 不能回显

集合的非空判断

代码语言:javascript
复制
th:if="${not #lists.isEmpty(自定义集合)}"

字符串拼接

代码语言:javascript
复制
<span th:text="|Welcome to HeBei, ${user.name}!|">
//这实际上相当于:
<span th:text="'Welcome to HeBei, ' + ${user.name} + '!'">
//文字替换可以与其他类型的表达相结合:
<span th:text="${onevar} + ' ' + |${twovar}, ${threevar}|">

小数(四舍五入)

代码语言:javascript
复制
//显示1.24
th:text="${#numbers.formatDecimal(1.235, 1, 2)}"

a标签-超链接

代码语言:javascript
复制
<a th:href="@{/user/doUpdate/(id=${companyUser.id},username=${user.username})}">view</a>
<a th:href="@{/user/{user.id}/getUserByUserName>view</a>

三元运算符判断

代码语言:javascript
复制
th:text="'Execution mode is ' + ( ('0'!='0')? 'Development' : 'Production')"

操作过程

Pom

代码语言:javascript
复制
<!-- thymeleaf 需要导入该配置,这样才能使用thymeleaf -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Application.properties

代码语言:javascript
复制
# thymeleaf配置
# 注释的部分是Thymeleaf默认的配置,如有其它需求可以自行更改
# spring.thymeleaf.prefix=classpath:/template/
# spring.thymeleaf.suffix=html
# spring.thymeleaf.mode=HTML5
# spring.thymeleaf.encoding=UTF-8
# spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false

Controller

SpringBoot会根据return "index/hello"的返回值,自动找到类路径下的templates文件夹的login.html,具体的前后缀组装原则,可以在ThymeleafProperties,双击shift快捷键,输入“ThymeleafProperties”,关键的代码如下

代码语言:javascript
复制
public class ThymeleafProperties {
	private static final Charset DEFAULT_ENCODING;
    public static final String DEFAULT_PREFIX = "classpath:/templates/"; //前缀
    public static final String DEFAULT_SUFFIX = ".html";//后缀
    private boolean checkTemplate = true;
    private boolean checkTemplateLocation = true;
    private String prefix = "classpath:/templates/";//类路径下的templates文件夹
    private String suffix = ".html";
    private String mode = "HTML";
}
代码语言:javascript
复制
package com.spring.master.spring.thymeleaf;

import com.google.gson.Gson;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;

/**
 * @author Huan Lee
 * @version 1.0
 * @date 2020-09-25 17:24
 * @describtion 业精于勤,荒于嬉;行成于思,毁于随。
 */
@Controller
@RequestMapping(value = "/thymeleaf")
public class ThymeleafController {

    /**
     * 测试:thymeleaf
     * @return
     */
    @GetMapping("/login")
    public String hello(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
        Person person = new Person();
        person.setName("thymeleaf");
        model.addAttribute("user", person);
        return "login";
    }

    /**
     * 测试:thymeleaf
     * @return
     */
    @GetMapping("/hello")
    public String hello(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
        PersonVO person = new PersonVO();
        person.setName("thymeleaf");
        model.addAttribute("user", person);
        return "index/hello";
    }

    /**
     *
     * @param name
     * @param model
     * @return
     */
    @GetMapping("/create")
    public String createMappingGet(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) throws IOException {
        model.addAttribute("name", name);
        model.addAttribute("clusterInfo", "Green");
        return "index/mapping";
    }

    @PostMapping("/create")
    public String createMappingPost(@RequestParam(name="source") String source, Model model) throws IOException {

        // TODO 可以进行表单提交之后的操作

        //防止post重复提交
        return "redirect:/thymeleaf/create";
    }
}
代码语言:javascript
复制
package com.spring.master.spring.thymeleaf;

import lombok.Data;

/**
 * @author Huan Lee
 * @version 1.0
 * @date 2020-09-25 17:42
 * @describtion 业精于勤,荒于嬉;行成于思,毁于随。
 */
@Data
public class Person {

    private String name;
}

Html

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>学生管理系统登陆界面</title>
    <link rel="stylesheet" href="layui/css/layui.css" th:href="@{/layui/css/layui.css}" media="all"/>
    <link rel="stylesheet" href="css/login.css" th:href="@{/css/login.css}" media="all"/>
    <style>
        /* 覆盖原框架样式 */
        .layui-elem-quote{background-color: inherit!important;}
        .layui-input, .layui-select, .layui-textarea{background-color: inherit; padding-left: 30px;}
    </style>
</head>
<body>
<!-- Head -->
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-sm12 layui-col-md12 zyl_mar_01">
            <blockquote class="layui-elem-quote">学生管理系统后台登陆界面</blockquote>
        </div>
    </div>
</div>
<!-- Head End -->

<!-- Carousel -->
<div class="layui-row">
    <div class="layui-col-sm12 layui-col-md12">
        <div class="layui-carousel zyl_login_height" id="zyllogin" lay-filter="zyllogin">
            <div carousel-item="">
                <div>
                    <div class="zyl_login_cont"></div>
                </div>
                <div>
                    <img src="images/01.jpg" th:src="@{/images/01.jpg}"/>
                </div>
                <div>
                    <div class="background">
                        <span></span><span></span><span></span>
                        <span></span><span></span><span></span>
                        <span></span><span></span><span></span>
                        <span></span><span></span><span></span>
                    </div>
                </div>
                <div>
                    <img src="images/03.jpg" th:src="@{/images/03.jpg}"/>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Carousel End -->

<!-- Footer -->
<div class="layui-row">
    <div class="layui-col-sm12 layui-col-md12 zyl_center zyl_mar_01">
        © 2019 - luojay学生管理系统登陆登陆界面版权所有
    </div>
</div>
<!-- Footer End -->



<!-- LoginForm -->
<div class="zyl_lofo_main">
    <fieldset class="layui-elem-field layui-field-title zyl_mar_02">
        <legend>欢迎登陆学生管理系统</legend>
    </fieldset>
    <div class="layui-row layui-col-space15">
        <form class="layui-form zyl_pad_01" action="">
            <div class="layui-col-sm12 layui-col-md12">
                <div class="layui-form-item">
                    <input type="text" name="userName" lay-verify="required|userName" autocomplete="off" placeholder="账号" class="layui-input">
                    <i class="layui-icon layui-icon-username zyl_lofo_icon"></i>
                </div>
            </div>
            <div class="layui-col-sm12 layui-col-md12">
                <div class="layui-form-item">
                    <input type="password" name="nuse" lay-verify="required|pass" autocomplete="off" placeholder="密码" class="layui-input">
                    <i class="layui-icon layui-icon-password zyl_lofo_icon"></i>
                </div>
            </div>
            <div class="layui-col-sm12 layui-col-md12">
                <div class="layui-row">
                    <div class="layui-col-xs4 layui-col-sm4 layui-col-md4">
                        <div class="layui-form-item">
                            <input type="text" name="vercode" id="vercode" lay-verify="required|vercodes" autocomplete="off" placeholder="验证码" class="layui-input" maxlength="4">
                            <i class="layui-icon layui-icon-vercode zyl_lofo_icon"></i>
                        </div>
                    </div>
                    <div class="layui-col-xs4 layui-col-sm4 layui-col-md4">
                        <div class="zyl_lofo_vercode zylVerCode" onclick="zylVerCode()"></div>
                    </div>
                </div>
            </div>
            <div class="layui-col-sm12 layui-col-md12">
                <button class="layui-btn layui-btn-fluid" lay-submit="" lay-filter="demo1">立即登录</button>
            </div>
        </form>
    </div>
</div>
<!-- LoginForm End -->


<!-- Jquery Js -->
<script type="text/javascript" src="js/jquery.min.js" th:src="@{/js/jquery.min.js}"></script>
<!-- Layui Js -->
<script type="text/javascript" src="layui/layui.js" th:src="@{/layui/layui.js}"></script>
<!-- Jqarticle Js -->
<script type="text/javascript" src="js/jparticle.min.js" th:src="@{/js/jparticle.min.js}"></script>
<!-- ZylVerificationCode Js-->
<script type="text/javascript" src="js/zylVerificationCode.js" th:src="@{/js/zylVerificationCode.js}"></script>
<script>
    layui.use(['carousel', 'form'], function(){
        var carousel = layui.carousel
            ,form = layui.form;

        //自定义验证规则
        form.verify({
            userName: function(value){
                if(value.length < 5){
                    return '账号至少得5个字符';
                }
            }
            ,pass: [/^[\S]{6,12}$/,'密码必须6到12位,且不能出现空格']
            ,vercodes: function(value){
                //获取验证码
                var zylVerCode = $(".zylVerCode").html();
                if(value!=zylVerCode){
                    return '验证码错误(区分大小写)';
                }
            }
            ,content: function(value){
                layedit.sync(editIndex);
            }
        });

        //监听提交
        form.on('submit(demo1)', function(data){
            layer.alert(JSON.stringify(data.field),{
                title: '最终的提交信息'
            })
            return false;
        });


        //设置轮播主体高度
        var zyl_login_height = $(window).height()/1.3;
        var zyl_car_height = $(".zyl_login_height").css("cssText","height:" + zyl_login_height + "px!important");


        //Login轮播主体
        carousel.render({
            elem: '#zyllogin'//指向容器选择器
            ,width: '100%' //设置容器宽度
            ,height:'zyl_car_height'
            ,arrow: 'always' //始终显示箭头
            ,anim: 'fade' //切换动画方式
            ,autoplay: true //是否自动切换false true
            ,arrow: 'hover' //切换箭头默认显示状态||不显示:none||悬停显示:hover||始终显示:always
            ,indicator: 'none' //指示器位置||外部:outside||内部:inside||不显示:none
            ,interval: '5000' //自动切换时间:单位:ms(毫秒)
        });

        //监听轮播--案例暂未使用
        carousel.on('change(zyllogin)', function(obj){
            var loginCarousel = obj.index;
        });

        //粒子线条
        $(".zyl_login_cont").jParticle({
            background: "rgba(0,0,0,0)",//背景颜色
            color: "#fff",//粒子和连线的颜色
            particlesNumber:100,//粒子数量
            //disableLinks:true,//禁止粒子间连线
            //disableMouse:true,//禁止粒子间连线(鼠标)
            particle: {
                minSize: 1,//最小粒子
                maxSize: 3,//最大粒子
                speed: 30,//粒子的动画速度
            }
        });

    });

</script>
</body>
</html>
代码语言:javascript
复制
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Springboot thymeleaf test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <link rel="stylesheet" th:href="@{/templates/css/main.css}"/>

</head>
<body>

<form action="/spring-master/thymeleaf/create" method="post" onsubmit="return confirm('确认要提交吗?');">

    要创建的Mapping:
    <br />

    <textarea rows = "50" cols = "80" name = "source">
        在这里.....
    </textarea>
    <br />
    <input type="submit" value="Update User">
</form>
</body>
</html>
代码语言:javascript
复制
.navbar-label {
    color: #008000;
    font-size: 50px;
}
代码语言:javascript
复制
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Springboot thymeleaf test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

    <link rel="stylesheet" th:href="@{/templates/css/main.css}"/>

</head>
<body>
<div>
    <div>
        <label class="navbar-label" th:text="${user.getName()}">Hello World</label>
    </div>
</div>
</body>
</html>

文件路径

spring-master/src/main/resources/templates/index/mapping.html

spring-master/src/main/resources/templates/login.html

spring-master/src/main/resources/templates/css/main.css

启动服务

代码语言:javascript
复制
http://localhost:3000/themeleaf-master/thymeleaf/login

http://localhost:3000/themeleaf-master/thymeleaf/create

http://localhost:3000/themeleaf-master/thymeleaf/hello

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 简介
  • 数据回显
    • input回填
      • 单选回填
        • 时间框回填
          • 下拉回填
            • textarea数据回显
              • 集合的非空判断
                • 字符串拼接
                  • 小数(四舍五入)
                    • a标签-超链接
                      • 三元运算符判断
                      • 操作过程
                        • Pom
                          • Application.properties
                            • Controller
                              • Html
                                • 启动服务
                                相关产品与服务
                                验证码
                                腾讯云新一代行为验证码(Captcha),基于十道安全栅栏, 为网页、App、小程序开发者打造立体、全面的人机验证。最大程度保护注册登录、活动秒杀、点赞发帖、数据保护等各大场景下业务安全的同时,提供更精细化的用户体验。
                                领券
                                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档