栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot-12视图解析与模板引擎(thymeleaf)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot-12视图解析与模板引擎(thymeleaf)

1、视图解析

概念:springboot处理完请求想要跳转页面的位置;

SpringBoot默认不支持 JSP,需要引入第三方模板引擎技术实现页面渲染。

实现:

  • 转发
  • 重定向
  • 自定义视图
2、模板引擎(thymeleaf)

thymeleaf 不适用高并发
2.1 基本语法

  • 1、表达式
    表达式名字——》语法——》用途
    变量取值——》${…} ——》获取请求域、session域、对象等值
    选择变量——》*{…}——》获取上下文对象值
    消息——》#{…}——》获取国际化等值
    链接——》@{…} ——》生成链接
    片段表达式——》~{…}——》jsp:include 作用,引入公共页面片段

  • 2、字面量
    文本值: ‘one text’ , ‘Another one!’ ,…数字: 0 , 34 , 3.0 , 12.3 ,…布尔值: true , false
    空值: null
    变量: one,two,… 变量不能有空格

  • 3、文本操作
    字符串拼接: +
    变量替换: |The name is ${name}|

  • 4、数学运算
    运算符: + , - , * , / , %

  • 5、布尔运算
    运算符: and , or
    一元运算: ! , not

  • 6、比较运算
    比较: > , < , >= , <= ( gt , lt , ge , le )等式: == , != ( eq , ne )

  • 7、条件运算
    If-then: (if) ? (then)
    If-then-else: (if) ? (then) : (else)
    Default: (value) ?: (defaultvalue)

  • 8、特殊操作
    无操作: _

参考:https://www.yuque.com/atguigu/springboot/vgzmgh#E21jG
h5兼容的标签写法:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#setting-value-to-specific-attributes

2.2 使用

  • 2.2.1 导入依赖:
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        

自动配置好了thymeleaf

@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration { }
  • 所有thymeleaf的配置值都在 ThymeleafProperties
  • 配置好了 SpringTemplateEngine
  • 配好了 ThymeleafViewResolver
  • 我们只需要直接开发页面
//默认跳转的文件位置
  public static final String DEFAULT_PREFIX = "classpath:/templates/";
//识别后缀名为html的页面
  public static final String DEFAULT_SUFFIX = ".html";  //xxx.html

  • 2.2.2 实现

添加头部

!--添加头部,即可使用thymeleaf表达式-->

html内容






    
    Title


1-转义测试


2-遍历测试

接口:

  • 通常给Model添加内容,会自动放在请求域中。
  • 给msg和user添加内容,html自动识别并赋值。
package com.springboot.Controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Arrays;

@Controller
public class ThymeleafController {

    @RequestMapping("/thymeleaf")
    //给Model的数据都会放在请求域中
    public String test(Model model){
        //转义
        model.addAttribute("msg","你好,springboot");
        //遍历
        model.addAttribute("users", Arrays.asList("yan1","yan2","yan3"));

        return "thymeleaf";
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/328058.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号