no6-开发web应用第二次课-Thymeleaf学习

飞一样的编程
飞一样的编程
擅长邻域:Java,MySQL,Linux,nginx,springboot,mongodb,微信小程序,vue

分类: springboot 专栏: springboot学习 标签: Thymeleaf学习

2023-03-20 17:09:47 796浏览

Thymeleaf学习

1.认识Thymeleaf

模板引擎:是为了用户界面和业务数据分离而产生的,它可以将业务数据动态填充到模板中,并且生成特定的Html文件,这种设计大大的提升了开发效率,也使得代码重用更加容易。

常见的模板引擎有JSP、Velocity、 FreeMarker、 Thymeleaf。

SpringBoot官方推荐的Thymeleaf语法更简单,功能更强大。

2.使用步骤

  1. 引入依赖
 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>


        <!--jquery-->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.4.1</version>
        </dependency>

        <!--redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!--fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.25</version>
        </dependency>

        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
        </dependency>
  1. 编写yaml配置文件或者properties文件
spring.thymeleaf.cache=false

mybatis.mapper-locations=mapper/*.xml
#打印sql语句
logging.level.com.bdqn.ch4thymeleaf.dao=debug
#开启驼峰命名,默认是不开启的
#mybatis.configuration.map-underscore-to-camel-case=true

spring.datasource.url=jdbc:mysql:///assay?characterEncoding=utf8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
#redis的配置可以省略,直接用默认的就行

前缀后缀 可以省略不写

  
spring:
	thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
    encoding: UTF-8
    mode: HTML5
    cache: false
    servlet:
      content-type: text/html
    check-template-location: true	
  1. 编写页面代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<h1>核酸检测系统</h1>
<form action="/medicalAssay/list" method="post" style="display: inline">
    <select name="hospitalId" id="selectHospital">
        <option value="">-请选择-</option>
    </select>
    <input type="submit" value="查询">
</form>
<button >新增</button>

<table border="1">
    <tr>
        <td>被检测人</td>
        <td>被检测人手机号</td>
        <td>被检查人身份证号</td>
        <td>检测机构</td>
        <td>检测日期</td>
        <td>检测结果</td>
        <td>操作</td>
    </tr>
    <tr th:each="assay:${list}">
        <td th:text="${assay.assayUser}"></td>
        <td th:text="${assay.phone}"></td>
        <td th:text="${assay.cardNum}"></td>
        <td th:text="${assay.hospitalName}"></td>
        <td th:text="${#dates.format(assay.assayTime,'yyyy-MM-dd')}"></td>
        <td th:text="${assay.assayResult == 1 ? '确诊': '检测中'}"></td>
        <td><a href="javascript:;" th:onclick="update(this,[[${assay.id}]])">确诊</a></td>
    </tr>
</table>

<script src="/webjars/jquery/3.4.1/jquery.js"></script>
<script th:inline="javascript">

    $(function () {
        //设置隔行变色
        $("tr:even:not(:first)").css("background-color","#b59a9a")
        $("tr:first").css("background-color","gray")
        var list = [[${list}]];
        var hospitalId = [[${hospitalId}]]
        console.log(list)
        if (list == null) {
            window.location.href="/medicalAssay/list"
        }else{
            //发送ajax获取医院名字加载下拉列表

            $.ajax({
                url:'/hospital/findAll',
                method:'get',
                dataType:'json',
                success:function (data) {
                    console.log(data)
                    var optionHtml="<option value=\"\">-请选择-</option>"
                    for (let i = 0; i < data.length; i++) {
                        if (hospitalId == data[i].id){
                            optionHtml+="<option selected value=\""+data[i].id+"\">"+data[i].name+"</option>"
                        }else{
                            optionHtml+="<option  value=\""+data[i].id+"\">"+data[i].name+"</option>"

                        }
                    }
                    $("#selectHospital").html(optionHtml)
                }
            })
        }

    })

    function update(that,aid) {
        if (confirm("确定是修改为确诊状态吗?")) {
            $.ajax({
                url: '/medicalAssay',
                method:'put',
                data:{"id":aid,"assayResult":1},
                dataType: "json",
                success:function (data) {
                    $(that).parent().prev().html("确诊")
                }
            })
        }

    }
</script>
</body>
</html>

注意:<html lang="en" xmlns:th="http://www.thymeleaf.org">

3.基本语法:

th:switch/th:case

<div th:switch="${sex}">
  <p th:case="1">性别:男</p>
  <p th:case="2">性别:女</p>
  <p th:case="*">性别:未知</p>
</div>

th:attr 给属性赋值

<input type="hidden" name="userId" th:attr="value=${userId}">

字符串拼接

一种是字面量拼接

<a href="#" th:text="'第'+${sex}+'页,共' +${sex}+ '页'"> </a>

另一种更优雅的方式,使用"|”减少了字符串的拼接

<a href="#" th:text= "|第${sex}页,共${sex}页|"> </a>

三元运算

<span th:text="${sex eq '1'} ? '男': '女'">未知</span>
  • 日期类型格式化
<span th:text="${#dates.format(createTime,'yyyy-MM-dd HH:mm:ss')}"></span>

循环遍历

<table class="table">
    <tr>
        <th>ID</th>
        <th>商品名称</th>
        <th>商品价格</th>
        <th>商品数量</th>
    </tr>
    <tr th:each="p : ${data}">
        <td th:text="${p.id}">默认ID</td>
        <td th:text="${p.name}">默认商品名称</td>
        <td th:text="${p.price}">默认商品价格</td>
        <td th:text="${p.amount}">默认商品数量</td>
    </tr>
</table>

内联[ [ ] ]

<script th:inline="javascript">
    var user = [[${user.username}]];
      alert(user);
</script>

参考文章:

https://blog.csdn.net/dong_19890208/article/details/61914964

基本语法:

https://www.jianshu.com/p/d1370aeb0881

4.boot项目redis操作

  <!--redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
 @Resource
    StringRedisTemplate stringRedisTemplate;
@Override
    public List<Hospital> findAll() {

        if( stringRedisTemplate.hasKey("hospitals")){
            String hospitals = stringRedisTemplate.opsForValue().get("hospitals");
            return JSON.parseArray(hospitals,Hospital.class);

        }else{
            List<Hospital> hospitals = hospitalDao.selectListByObj(new Hospital());
            stringRedisTemplate.opsForValue().set("hospitals", JSON.toJSONString(hospitals));
            return hospitals;
        }


    }

好博客就要一起分享哦!分享海报

此处可发布评论

评论(1展开评论

蓝色妖姬 能力:10

2023-06-15 10:16:20

学的总忘记,温习中
点击查看更多评论

展开评论

您可能感兴趣的博客

客服QQ 1913284695