关于thymeleaf:Thymeleaf-在HTML定义数组常量并遍历

概述个别状况下只可能从Controller传一个数组或者List的变量到HTML来遍历,然而也有场景是须要间接在HTML上定义变量,但发现Thymeleaf这么简略的办法都没有,找了内置的arrays、lists都没有方法定义数组,最初找到了strings有一个办法strings.arraySplit,能够用一个字符串截取逗号,来解决动态数组的定义。 例子间接遍历渲染 <li th:each="fruit : ${#strings.arraySplit('苹果,西瓜,榴莲',',')}" th:text="${fruit}"></li>定义变量并渲染 <div th:with="fruits=${#strings.arraySplit('苹果,西瓜,榴莲,凤梨',',')}"> <li th:each="fruit : ${fruits}" th:text="${fruit}"></li></div>另外一种办法截取字符串的办法如同有点不太好看,也有另外一种办法,能够重写Thymeleaf的 org.thymeleaf.expression.Arrays 类,减少一个“脱裤子放屁”的办法。 public Object[] asList(Object[] objects) { return objects;}HTML上应用 <ul> <li th:each="fruit : ${#arrays.asList('苹果,西瓜,榴莲')}" th:text="${fruit}"></li></ul>

March 9, 2023 · 1 min · jiezi

关于thymeleaf:搞定后台应用必备技术带你Thymeleaf学到精

Thymeleaf是什么?Thymeleaf是一种服务器端Java模板引擎,它通过在html标签中嵌入非凡的语法糖,实现双击html文件即可在浏览器中预览页面成果,又能够在服务端解析解决后渲染出动静页面; 这对于解决UI模板的前端设计人员十分敌对,所见即所得。 同时对于服务器端人员来说,只需在html标签中嵌入语法糖,即可启用模板性能,渲染出动静页面,实现了前端设计人员和后端开发人员的职责拆散。 Thymeleaf很容易学习与了解,并有着本人显明的特色,适宜在后盾利用,以及各种治理类零碎中应用。 能源节点的Thymeleaf教程将一步一步详解解说Thymeleaf模板引擎技术,全面把握Thymeleaf模板技术,并在理论我的项目开发中得心应手应用Thymeleaf模板技术。Thymeleaf在线学习: https://www.bilibili.com/vide... Thymeleaf材料下载: http://www.bjpowernode.com/?s... Thymeleaf的劣势以html的属性呈现,保障html的残缺语法结构不被毁坏;浏览器可间接预览模板文件,无需服务器端反对;提供了大量内置对象,内置工具类;语法简略,学习难度低;反对html,js,raw等多种模板类型;适应人群:有肯定的Java Web开发根底,把握SpringBoot,或者有工作教训的人群。 课程目录:第一章 Thymeleaf小试牛刀1-1 thymeleaf-模板工作形式 1-2 thymeleaf-文档 1-3 thymeleaf-第一个例子 1-4 thymeleaf-模板应用数据 1-5 thymeleaf-应用模板文件 1-6 thymeleaf-设置模板前缀后缀 1-7 thymeleaf-springboot环境搭建 1-8 thymeleaf-测试springboot中应用模板 第二章 Thymeleaf语法2-1 thymeleaf-变量表达式根本语法-1 2-2 thymeleaf-变量表达式根本语法-2 2-3 thymeleaf-链接表达式 2-4 thymeleaf-链接表达式传参数 2-5 thymeleaf-国际化介绍 2-6 thymeleaf-自定义LocalResolver 2-7 thymeleaf-国际化模板定义 2-8 thymeleaf-调式国际化 2-9 thymeleaf-文本表达式 2-10 thymeleaf-数字表达式 2-11 thymeleaf-布尔表达式 2-12 thymeleaf-null和空字符串 2-13 thymeleaf-逻辑表达式 2-14 thymeleaf-三元运算符-1 2-15 thymeleaf-三元运算符-2 2-16 thymeleaf-设置属性值 2-17 thymeleaf-attr设置任意属性值 2-18 thymeleaf-设置属性值 2-19 thymeleaf-同时设置多个属性值 2-20 thymeleaf-boolean设置 2-21 thymeleaf-设置标签体文本 ...

November 23, 2021 · 1 min · jiezi

关于thymeleaf:Thymeleafltleeqnegegtnotmod表示的含义

在 Thymeleaf 之中逻辑运算能够应用上面的一些运算符来实现。例如:and、or、关系比拟(>、<、>=、<=、==、!=、lt、gt、le、ge、eq、ne等)。 上面阐明一下:lt、gt、le、ge、eq、ne所代表的含意: lt:less than 小于le:less than or equal to 小于等于eq:equal to 等于ne:not equal to 不等于ge:greater than or equal to 大于等于gt:greater than 大于not: 非运算mod:取模and:与运算or:或运算

November 6, 2020 · 1 min · jiezi

关于thymeleaf:404500thymeleaf模板引擎

如果加了多余的依赖,然而又不配置,可能服务都启动不起来! Thymeleaf:模板解析引擎他负责将Model中的数据,放到html中去,thymeleaf能够解析html

September 25, 2020 · 1 min · jiezi

Spring-Boot-2X三使用-Spring-MVC-MyBatis-Thymeleaf-开发-web-应用

前言Spring MVC 是构建在 Servlet API 上的原生框架,并从一开始就包含在 Spring 框架中。本文主要通过简述 Spring MVC 的架构及分析,并用 Spring Boot + Spring MVC + MyBatis (SSM)+ Thymeleaf(模板引擎) 框架来简单快速构建一个 Web 项目。 Web MVC 架构及分析MVC 三层架构如图所示,红色字体代表核心模块。其中 MVC 各分层分别为: Model (模型层)处理核心业务(数据)逻辑,模型对象负责在数据库中存取数据。这里的“数据”不仅限于数据本身,还包括处理数据的逻辑。View(视图层)用于展示数据,通常数据依据模型数据创建。Controller(控制器层)用于处理用户输入请求和响应输出,从试图读取数据,控制用户输入,并向模型发送数据。Controller 是在 Model 和 View 之间双向传递数据的中间协调者。 Spring MVC 架构及分析Spring MVC 处理一个 HTTP 请求的流程,如图所示:整个过程详细介绍:1.用户发送请求至前端控制器 DispatcherServlet。2.DispatcherServlet 收到请求调用处理器映射器 HandlerMapping。3.处理器映射器根据请求 URL 找到具体的 Controller 处理器返回给 DispatcherServlet。4.DispatcherServlet 通过处理器适配器 HandlerAdapter 调用 Controller 处理请求。5.执行 Controller 处理器的方法。6.Controller 执行完成返回 ModelAndView。7.HandlerAdapter 将 Controller 执行结果 ModelAndView 返回给 DispatcherServlet。8.DispatcherServlet 将 ModelAndView 的 ViewName 传给视图解析器 ViewReslover。9.ViewReslover 解析后返回具体的视图 View。10.DispatcherServlet 传递 Model 数据给 View,对 View 进行渲染(即将模型数据填充至视图中)。11-12.DispatcherServlet 响应用户。 ...

November 5, 2019 · 3 min · jiezi

SpringBoot集成Thymeleaf模版引擎

一、前言Thymeleaf 是一个优秀的、面向Java 的XML、HTML/HTML5 页面模板,具有丰富的标签语言和函数。因此,在使用Spring Boot 框架进行页面设计时, 一般都会选择Thymeleaf 模板。类似thymeleaf的模版还有freemarker,推荐使用thymeleaf,前后端分离。二、springboot集成Thymeleaf模版引擎pom.xml引入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>application.properties中配置: ##去除thymeleaf的html严格校验spring.thymeleaf.mode=LEGACYHTML5#设定thymeleaf文件路径 默认为src/main/resources/templatesspring.freemarker.template-loader-path=classpath:/templates在controller中书写相关代码,注意controller层中注解使用@controller,不要是用@RestController,否则就会出现页面返回字符串而不是正常的html页面。模版html页面中,也是需要引入thymeleaf: <html xmlns:th="http://www.thymeleaf.org">最后启动项目即可三、需要注意的问题通过以上配置后,我们发现,有时候自己写的html页面会无法解析,这种情况就有可能是因为使用springboot的thymeleaf模板时,默认会对HTML进行严格的检查,导致当标签没有闭合时就会通不过。nekohtml这个依赖可以解决这一问题。为了解决html严格校验报错的问题,可以在pom.xml增添依赖nekohtml <dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>1.9.15</version> </dependency>

June 21, 2019 · 1 min · jiezi

极简-Spring-Boot-整合-Thymeleaf-页面模板

虽然现在慢慢在流行前后端分离开发,但是据松哥所了解到的,还是有一些公司在做前后端不分的开发,而在前后端不分的开发中,我们就会需要后端页面模板(实际上,即使前后端分离,也会在一些场景下需要使用页面模板,例如邮件发送模板)。 <!--more--> 早期的 Spring Boot 中还支持使用 Velocity 作为页面模板,现在的 Spring Boot 中已经不支持 Velocity 了,页面模板主要支持 Thymeleaf 和 Freemarker ,当然,作为 Java 最最基本的页面模板 Jsp ,Spring Boot 也是支持的,只是使用比较麻烦。 松哥打算用三篇文章分别向大家介绍一下这三种页面模板技术。 今天我们主要来看看 Thymeleaf 在 Spring Boot 中的整合! Thymeleaf 简介Thymeleaf 是新一代 Java 模板引擎,它类似于 Velocity、FreeMarker 等传统 Java 模板引擎,但是与传统 Java 模板引擎不同的是,Thymeleaf 支持 HTML 原型。 它既可以让前端工程师在浏览器中直接打开查看样式,也可以让后端工程师结合真实数据查看显示效果,同时,SpringBoot 提供了 Thymeleaf 自动化配置解决方案,因此在 SpringBoot 中使用 Thymeleaf 非常方便。 事实上, Thymeleaf 除了展示基本的 HTML ,进行页面渲染之外,也可以作为一个 HTML 片段进行渲染,例如我们在做邮件发送时,可以使用 Thymeleaf 作为邮件发送模板。 另外,由于 Thymeleaf 模板后缀为 .html,可以直接被浏览器打开,因此,预览时非常方便。 整合创建项目Spring Boot 中整合 Thymeleaf 非常容易,只需要创建项目时添加 Thymeleaf 即可: ...

June 13, 2019 · 3 min · jiezi

SpringBoot引入Thymeleaf

1.Thymeleaf简介 Thymeleaf是个XML/XHTML/HTML5模板引擎,可以用于Web与非Web应用 Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模,Thymeleaf的可扩展性也非常棒。你可以使用它定义自己的模板属性集合,这样就可以计算自定义表达式并使用自定义逻辑,Thymeleaf还可以作为模板引擎框架。2.引入Thymeleaf引入依赖在maven(pom.xml)中直接引入:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>配置Thymeleaf在application.yml配置Thymeleafserver: port: 8000spring: thymeleaf: cache: false # 关闭页面缓存 encoding: UTF-8 # 模板编码 prefix: classpath:/templates/ # 页面映射路径 suffix: .html # 试图后的后缀 mode: HTML5 # 模板模式# 其他具体配置可参考org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties# 上面的配置实际上就是注入该类的属性值demo示例创建IndexController@Controllerpublic class IndexController { // 返回视图页面 @RequestMapping(“index”) public String index(){ return “index”; }} 创建index.html<!DOCTYPE html><html lang=“en”><head> <meta charset=“UTF-8”> <title>Title</title></head><body> Hello Thymeleaf!</body></html> 创建TestController@RestControllerpublic class TestController { // 返回整个页面 @RequestMapping("/test") public ModelAndView test(){ return new ModelAndView(“test”); }} 创建test.html<!DOCTYPE html><html lang=“en”><head> <meta charset=“UTF-8”> <title>Title</title></head><body>Hello Thymeleaf! </br>By: ModelAndView</body></html>3.测试结果4.Thymeleaf基础语法及使用1.引入标签 html标签里引入xmlns:th=“http://www.thymeleaf.org"才能使用th:这样的语法 2.引入URL @{…} 例如:<a th:href=”@{http://www.baidu.com}">绝对路径</a> 是访问绝对路径下的URL, <a th:href="@{/}">相对路径</a> 是访问相对路径下的URL。<a th:href="@{css/bootstrap.min.css}">是引入默认的static下的css文件夹下的bootstrap文件,类似的标签有: th:href 和 th:src 3.获取变量 通过${}取值,对于JavaBean的话,使用变量名.属性名获取 4.字符串替换<span th:text="‘Welcome to our application, ’ + ${user.name} + ‘!’"></span>或者<span th:text="|Welcome to our application, ${user.name}!|"></span>注意:|…|中只能包含变量表达式${…},不能包含其他常量、条件表达式等5.运算符 在表达式中可以使用各类算术运算符 例如 (+, -, , /, %) 例如:th:with=“isEven=(${stat.number} % 1 == 0)” 逻辑运算符 (>, <, <=,>=,==,!=) 需要注意的是使用<,>的时候需要转义th:if="${stat.number} &gt; 1"th:text="‘Execution mode is ’ + ( (${execMode} == ‘dev’)? ‘Development’ : ‘Production’)“6.条件 if/unless th:if是该标签在满足条件的时候才会显示,unless是不成立时候才显示<a th:href=”@{/login}" th:unless=${user.number != null}>Login</a> switch thymeleaf支持switch结构,默认属性(default)用表示<div th:switch="${user.role}"> <p th:case="‘admin’">User is an administrator</p> <p th:case="#{roles.manager}">User is a manager</p> <p th:case="">User is some other thing</p></div>7.循环<tr th:each=“prod : ${prods}"> <td th:text="${prod.name}">Onions</td> <td th:text="${prod.price}">2.41</td> <td th:text="${prod.inStock}? #{true} : #{false}">yes</td></tr>8.Utilities内置在Context中,可以直接通过#访问#dates #calendars #numbers #strings arrays lists sets maps … 5.小结 本文讲述了如何在Spring Boot中引入模板引擎Thymeleaf以及Thymeleaf基础语法和实际使用本文GitHub地址:https://github.com/ishuibo/Sp… ...

April 3, 2019 · 1 min · jiezi

thymeleaf 简单应用

th:switch 应用<th:block th:switch="${mapResult.bidType}"> <th:block th:case="‘1’"> <head th:replace=“common/include-header :: header (${bidProjectTypeMap[mapResult.bidProjectType]}+‘公告变更’)”/> </th:block> <th:block th:case="‘2’"> <head th:replace=“common/include-header :: header (‘投标邀请变更’)”/> </th:block> <th:block th:case="*"> <head th:replace=“common/include-header :: header (${bidProjectTypeMap[mapResult.bidProjectType]}+‘公告变更’)”/> </th:block></th:block>判断对象属性是否存在<p class=“project-name” th:if="${#maps.containsKey(mapResult, ‘bidType’)}"><span th:text="${mapResult.bidType}"></span></p>另// 判断对象的属性是否存在var userMobile = [[${user?.mobile}]];页面定义变更 th:with<html xmlns:th=“http://www.thymeleaf.org” th:with=“COMPANY_NAME=‘聯成化學科技股份有限公司’">

March 7, 2019 · 1 min · jiezi

SpringBoot 实战 (十二) | 整合 thymeleaf

微信公众号:一个优秀的废人如有问题或建议,请后台留言,我会尽力解决你的问题。前言如题,今天介绍 Thymeleaf ,并整合 Thymeleaf 开发一个简陋版的学生信息管理系统。SpringBoot 提供了大量模板引擎,包含 Freemarker、Groovy、Thymeleaf、Velocity 以及 Mustache,SpringBoot 中推荐使用 Thymeleaf 作为模板引擎,因为 Thymeleaf 提供了完美的 SpringMVC 支持。Thymeleaf 是新一代 Java 模板引擎,在 Spring 4 后推荐使用。什么是模板引擎?Thymeleaf 是一种模板语言。那模板语言或模板引擎是什么?常见的模板语言都包含以下几个概念:数据(Data)、模板(Template)、模板引擎(Template Engine)和结果文档(Result Documents)。数据数据是信息的表现形式和载体,可以是符号、文字、数字、语音、图像、视频等。数据和信息是不可分离的,数据是信息的表达,信息是数据的内涵。数据本身没有意义,数据只有对实体行为产生影响时才成为信息。模板模板,是一个蓝图,即一个与类型无关的类。编译器在使用模板时,会根据模板实参对模板进行实例化,得到一个与类型相关的类。模板引擎模板引擎(这里特指用于Web开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档。结果文档一种特定格式的文档,比如用于网站的模板引擎就会生成一个标准的HTML文档。模板语言用途广泛,常见的用途如下:页面渲染文档生成代码生成所有 “数据+模板=文本” 的应用场景Thymeleaf 简介Thymeleaf 是一个 Java 类库,它是一个 xml/xhtml/html5 的模板引擎,可以作为 MVC 的 web 应用的 View 层。Thymeleaf 还提供了额外的模块与 SpringMVC 集成,所以我们可以使用 Thymeleaf 完全替代 JSP 。Thymeleaf 语法博客资料:http://www.cnblogs.com/nuoyia…官方文档:http://www.thymeleaf.org/docu…SpringBoot 整合 Thymeleaf下面使用 SpringBoot 整合 Thymeleaf 开发一个简陋版的学生信息管理系统。1、准备工作IDEAJDK1.8SpringBoot2.1.32、pom.xml 主要依赖<dependencies> <!– JPA 数据访问 –> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!– thymeleaf 模板引擎 –> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!– web 启动类 –> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!– mysql 数据库连接类 –> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency></dependencies>3、application.yaml 文件配置spring: # 数据库相关 datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=true username: root password: 123456 # jpa 相关 jpa: hibernate: ddl-auto: update # ddl-auto: 第一次启动项目设为 create 表示每次都重新建表,之后设置为 update show-sql: true4、实体类@Data@Entity@AllArgsConstructor@NoArgsConstructorpublic class Student { @Id @GeneratedValue /** * 主键 / private Long id; /* * 主键 / private Long studentId; /* * 姓名 / private String name; /* * 年龄 / private Integer age; /* * 专业 / private String major; /* * 宿舍 / private String dormitory; /* * 籍贯 / private String city; /@Temporal(TemporalType.TIMESTAMP)//将时间戳,转换成年月日时分秒的日期格式 @Column(name = “create_time”,insertable = false, updatable=false, columnDefinition = “timestamp default current_timestamp comment ‘注册时间’”) private Date createDate; @Temporal(TemporalType.TIMESTAMP)//将时间戳,转换成年月日时分秒的日期格式 @Column(name = “update_time”,insertable = false, updatable=true, columnDefinition = “timestamp default current_timestamp comment ‘修改时间’”) private Date updateDate;/}5、dao 层@Repositorypublic interface StudentRepository extends JpaRepository<Student, Long> {}6、service 层public interface StudentService { List<Student> findStudentList(); Student findStudentById(Long id); Student saveStudent(Student student); Student updateStudent(Student student); void deleteStudentById(Long id);}实现类:@Servicepublic class StudentServiceImpl implements StudentService { @Autowired private StudentRepository studentRepository; /** * 查询所有学生信息列表 * @return / @Override public List<Student> findStudentList() { Sort sort = new Sort(Direction.ASC,“id”); return studentRepository.findAll(sort); } /* * 根据 id 查询单个学生信息 * @param id * @return / @Override public Student findStudentById(Long id) { return studentRepository.findById(id).get(); } /* * 保存学生信息 * @param student * @return / @Override public Student saveStudent(Student student) { return studentRepository.save(student); } /* * 更新学生信息 * @param student * @return / @Override public Student updateStudent(Student student) { return studentRepository.save(student); } /* * 根据 id 删除学生信息 * @param id * @return / @Override public void deleteStudentById(Long id) { studentRepository.deleteById(id); }}7、controller 层 (Thymeleaf) 使用controller 层将 view 指向 Thymeleaf:@Controller@RequestMapping("/student")public class StudentController { @Autowired private StudentService studentService; /* * 获取学生信息列表 * @param map * @return / @GetMapping("/list") public String findStudentList(ModelMap map) { map.addAttribute(“studentList”,studentService.findStudentList()); return “studentList”; } /* * 获取保存 student 表单 / @GetMapping(value = “/create”) public String createStudentForm(ModelMap map) { map.addAttribute(“student”, new Student()); map.addAttribute(“action”, “create”); return “studentForm”; } /* * 保存学生信息 * @param student * @return / @PostMapping(value = “/create”) public String saveStudent(@ModelAttribute Student student) { studentService.saveStudent(student); return “redirect:/student/list”; } /* * 根据 id 获取 student 表单,编辑后提交更新 * @param id * @param map * @return / @GetMapping(value = “/update/{id}”) public String edit(@PathVariable Long id, ModelMap map) { map.addAttribute(“student”, studentService.findStudentById(id)); map.addAttribute(“action”, “update”); return “studentForm”; } /* * 更新学生信息 * @param student * @return / @PostMapping(value = “/update”) public String updateStudent(@ModelAttribute Student student) { studentService.updateStudent(student); return “redirect:/student/list”; } /* * 删除学生信息 * @param id * @return / @GetMapping(value = “/delete/{id}”) public String deleteStudentById(@PathVariable Long id) { studentService.deleteStudentById(id); return “redirect:/student/list”; }}简单说下,ModelMap 对象来进行数据绑定到视图。return 字符串,该字符串对应的目录在 resources/templates 下的模板名字。 @ModelAttribute 注解是用来获取页面 Form 表单提交的数据,并绑定到 Student 数据对象。8、studentForm 表单定义了一个 Form 表单用于注册或修改学生信息。<form th:action="@{/student/{action}(action=${action})}" method=“post” class=“form-horizontal”> <div class=“form-group”> <label for=“student_Id” class=“col-sm-2 control-label”>学号:</label> <div class=“col-xs-4”> <input type=“text” class=“form-control” id=“student_Id” name=“name” th:value="${student.studentId}" th:field="{student.studentId}"/> </div> </div> <div class=“form-group”> <label for=“student_name” class=“col-sm-2 control-label”>姓名:</label> <div class=“col-xs-4”> <input type=“text” class=“form-control” id=“student_name” name=“name” th:value="${student.name}" th:field="{student.name}"/> </div> </div> <div class=“form-group”> <label for=“student_age” class=“col-sm-2 control-label”>年龄:</label> <div class=“col-xs-4”> <input type=“text” class=“form-control” id=“student_age” name=“name” th:value="${student.age}" th:field="{student.age}"/> </div> </div> <div class=“form-group”> <label for=“student_major” class=“col-sm-2 control-label”>专业:</label> <div class=“col-xs-4”> <input type=“text” class=“form-control” id=“student_major” name=“name” th:value="${student.major}" th:field="{student.major}"/> </div> </div> <div class=“form-group”> <label for=“student_dormitory” class=“col-sm-2 control-label”>宿舍:</label> <div class=“col-xs-4”> <input type=“text” class=“form-control” id=“student_dormitory” name=“name” th:value="${student.dormitory}" th:field="{student.dormitory}"/> </div> </div> <div class=“form-group”> <label for=“student_city” class=“col-sm-2 control-label”>籍贯:</label> <div class=“col-xs-4”> <input type=“text” class=“form-control” id=“student_city” name=“writer” th:value="${student.city}" th:field="{student.city}"/> </div> </div> <div class=“form-group”> <div class=“col-sm-offset-3 col-sm-10”> <input class=“btn btn-primary” type=“submit” value=“提交”/>&nbsp;&nbsp; <input class=“btn” type=“button” value=“返回” onclick=“history.back()”/> </div> </div> </form>9、studentList 学生列表用于展示学生信息:<table class=“table table-hover table-condensed”> <legend> <strong>学生信息列表</strong> </legend> <thead> <tr> <th>学号</th> <th>姓名</th> <th>年龄</th> <th>专业</th> <th>宿舍</th> <th>籍贯</th> <th>管理</th> </tr> </thead> <tbody> <tr th:each=“student : ${studentList}"> <th scope=“row” th:text="${student.studentId}"></th> <td><a th:href=”@{/student/update/{studentId}(studentId=${student.id})}" th:text="${student.name}"></a></td> <td th:text="${student.age}"></td> <td th:text="${student.major}"></td> <td th:text="${student.dormitory}"></td> <td th:text="${student.city}"></td> <td><a class=“btn btn-danger” th:href="@{/student/delete/{studentId}(studentId=${student.id})}">删除</a></td> </tr> </tbody> </table>页面效果列表页面:点击按钮可注册学生信息注册/修改学生信息页面:点提交保存学生信息到数据库并返回列表页面有数据的列表页面:点击名字跳到注册/修改页面可修改学生信息,点击删除可删除学生信息后语如果本文对你哪怕有一丁点帮助,请帮忙点好看。你的好看是我坚持写作的动力。另外,关注之后在发送 1024 可领取免费学习资料。资料内容详情请看这篇旧文:Python、C++、Java、Linux、Go、前端、算法资料分享 ...

February 25, 2019 · 4 min · jiezi

Thymeleaf 的基本用法

Thymeleaf 的基本用法属于个人整理的文档,大部分内容来源自网络在这里我们没有打算使用SpringMVC进行整合使用或者说跟Spring Boot 一起使用我们在这里单独使用Servelet版本-算是为了给一些初学者提供部分代码Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎,类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用,但是总是看到说其效率有点低Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。Thymeleaf 开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、改jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。1.引入提示在html页面中引入thymeleaf命名空间,即,此时在html模板文件中动态的属性使用th:命名空间修饰 。<html lang=“en” xmlns:th=“http://www.thymeleaf.org”>这样才可以在其他标签里面使用th:这样的语法.这是下面语法的前提.2.变量表达式(获取变量值)<div th:text="‘你是否读过,’+${session.book}+’!!’"> 同EL表达式有些相似的效果,如果有数据,被替换 完成前后端分离效果(美工代码)</div>代码分析:1.可以看出获取变量值用$符号,对于javaBean的话使用变量名.属性名方式获取,这点和EL表达式一样2.它通过标签中的th:text属性来填充该标签的一段内容,意思是$表达式只能写在th标签内部,不然不会生效,上面例子就是使用th:text标签的值替换div标签里面的值,至于div里面的原有的值只是为了给前端开发时做展示用的.这样的话很好的做到了前后端分离.意味着div标签中的内容会被表达式${session.book}的值所替代,无论模板中它的内容是什么,之所以在模板中“多此一举“地填充它的内容,完全是为了它能够作为原型在浏览器中直接显示出来。3.访问spring-mvc中model的属性,语法格式为“${}”,如${user.id}可以获取model里的user对象的id属性 4.牛叉的循环<li th:each=“book : ${books}” >3.URL表达式(引入URL)重点!重点!重点!引用静态资源文件(CSS使用th:href,js使用使用th:src)href链接URL(使用th:href)代码分析1.最终解析的href为: /seconddemo/ /seconddemo/usethymeleaf?name=Dear 相对路径,带一个参数 /seconddemo/usethymeleaf?name=Dear&alis=Dear 相对路径,带多个参数 /seconddemo/usethymeleaf?name=Dear&alis=Dear 相对路径,带多个参数 /seconddemo/usethymeleaf/Dear 相对路径,替换URL一个变量 /seconddemo/usethymeleaf/Dear/Dear 相对路径,替换URL多个变量2.URL最后的(name=${name})表示将括号内的内容作为URL参数处理,该语法避免使用字符串拼接,大大提高了可读性3.@{/usethymeleaf}是Context相关的相对路径,在渲染时会自动添加上当前Web应用的Context名字,假设context名字为seconddemo,那么结果应该是/seconddemo/usethymeleaf,即URL中以”/“开头的路径(比如/usethymeleaf将会加上服务器地址和域名和应用cotextpath,形成完整的URL。4.th:href属性修饰符:它将计算并替换使用href链接URL 值,并放入的href属性中。5.th:href中可以直接使用静态地址4.选择或星号表达式表达式很像变量表达式,不过它们用一个预先选择的对象来代替上下文变量容器(map)来执行{customer.name}<div th:object="${session.user}"> <p>Name: <span th:text="{firstName}">Sebastian</span>.</p> <p>Surname: <span th:text="{lastName}">Pepper</span>.</p> <p>Nationality: <span th:text="{nationality}">Saturn</span>.</p> </div>//等价于<div> <p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p> <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p> <p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p></div>1.如果不考虑上下文的情况下,两者没有区别;星号语法评估在选定对象上表达,而不是整个上下文,什么是选定对象?就是父标签的值。上面的{title}表达式可以理解为${book.title}。(父对象) 2.当然,美元符号和星号语法可以混合使用小插曲:三和四的变量表达式、URL表达式所对应的属性都可以使用统一的方式:th.attr=“属性名=属性值”的方式来设置,参考第“七.设置属性值”部分5.文字国际化表达式j简单看一下就可以,文字国际化表达式允许我们从一个外部文件获取区域文字信息(.properties),用Key索引Value,还可以提供一组参数(可选).#{main.title} #{message.entrycreated(${entryId})} 可以在模板文件中找到这样的表达式代码: <table> <th th:text="#{header.address.city}"> <th th:text="#{header.address.country}"></table>6. 表达式支持的语法字面量(Literals)文本文字(Text literals): ‘one text’, ‘Another one!’,…数字文本(Number literals): 0, 34, 3.0, 12.3,…布尔文本(Boolean literals): true, false空(Null literal): null文字标记(Literal tokens): one , sometext文本操作(Text operations)字符串连接(String concatenation): +文本替换(Literal substitutions): |The name is ${name}|<div th:class="‘content’">…</div><span th:text="|Welcome to our application, ${user.name}!|">//Which is equivalent to:<span th:text="‘Welcome to our application, ’ + ${user.name} + ‘!’"><span th:text="${onevar} + ’ ’ + |${twovar}, ${threevar}|">算术运算(Arithmetic operations)二元运算符(Binary operators): + , - , * , / , %减号(Minus sign (unary operator)): -布尔操作(Boolean operations)Binary operators: and , orBoolean negation (unary operator): ! , not比较和等价(Comparisons and equality)Comparators: > , < , >= , <= ( gt , lt , ge , le )Equality operators: == , != ( eq , ne )条件运算符(Conditional operators)三元运算符If-then: (if) ? (then)If-then-else: (if) ? (then) : (else)Default: (value) ?: (defaultvalue)示例一: <h2 th:text="${expression} ? ‘Hello’ : ‘Something else’"></h2>示例二: <!– IF CUSTOMER IS ANONYMOUS –> <div th:if="${customer.anonymous}"> <div>Welcome, Gues!</div> </div> <!– ELSE –> <div th:unless="${customer.anonymous}"> <div th:text=" ‘Hi,’ + ${customer.name}">Hi, User</div> </div>Special tokens:No-Operation: _switch循环渲染列表数据是一种非常常见的场景,例如现在有n条记录需要渲染成一个表格或li列表标签该数据集合必须是可以遍历的,使用th:each标签代码分析:循环,在html的标签中,加入th:each=“value:${list}”形式的属性,如可以迭代prods的数据 又如带状态变量的循环: 利用状态变量判断:7.设置属性值1. th:attr 任何属性值,语法格式:th:attr=“属性名=属性值,[属性名=属性值]" 属性值如果是使用表达式的话:通常有URL表达式@{}和变量表达式${} 但此标签语法不太优雅 示例: th:attr=“action=@{/subscribe}” //当然也可以直接使用th:action th:attr=“src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" //可直接使用th:src th:attr=“value=#{subscribe.submit}”//可直接使用th:value <input type=“checkbox” name=“active” th:attr=“checked=${user.active}”/> 设置多个属性在同一时间,有两个特殊的属性可以这样设置: th:alt-title 和 th:lang-xmllang th:src=”@{/images/gtvglogo.png}” th:alt-title="#{logo}" 2.前置和后置添加属性值 th:attrappend 和 th:attrprepend 主要对class和style两个属性 class=“btn” th:attrappend=“class=${’ ’ + cssStyle}" 转换后:class=“btn warning” 3.还有两个特定的添加属性 th:classappend 和 th:styleappend 与上面的attrappend功能一样 class=“row” th:classappend="${prodStat.odd}? ‘odd’" 转换后:奇数行class=“row odd”,偶数行class=“row"8.内嵌变量Utilities为了模板更加易用,Thymeleaf还提供了一系列Utility对象(内置于Context中),可以通过#直接访问。dates : java.util.Date的功能方法类 calendars : 类似#dates,面向java.util.Calendar numbers : 格式化数字的功能方法类 strings : 字符串对象的功能类,contains,startWiths,prepending/appending等等 objects: 对objects的功能类操作 bools: 对布尔值求值的功能方法 arrays:对数组的功能类方法 lists: 对lists功能类方法 sets maps代码示例: ${#dates.format(dateVar, ‘dd/MMM/yyyy HH:mm’)} ${#dates.arrayFormat(datesArray, ‘dd/MMM/yyyy HH:mm’)} ${#dates.listFormat(datesList, ‘dd/MMM/yyyy HH:mm’)} ${#dates.setFormat(datesSet, ‘dd/MMM/yyyy HH:mm’)} ${#dates.createNow()} ${#dates.createToday()} ${#strings.isEmpty(name)} ${#strings.arrayIsEmpty(nameArr)} ${#strings.listIsEmpty(nameList)} ${#strings.setIsEmpty(nameSet)} ${#strings.startsWith(name,‘Don’)} // also array*, list* and set* ${#strings.endsWith(name,endingFragment)} // also array*, list* and set* ${#strings.length(str)} ${#strings.equals(str)} ${#strings.equalsIgnoreCase(str)} ${#strings.concat(str)} ${#strings.concatReplaceNulls(str)} ${#strings.randomAlphanumeric(count)}//产生随机字符串9.thymeleaf布局10.附录thymeleaf_3.0.5_中文参考手册 提取码:emk0 ...

December 29, 2018 · 2 min · jiezi