关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

云南大王-Spring Boot整合Thymeleaf视图层

发布时间:2020-04-13 00:00:00
目录Spring Boot整合ThymeleafSpring Boot整合Thymeleaf 的项目步骤Thymeleaf 语法详解 Spring Boot整合Thymeleaf Spring Boot整合Thymeleaf(Spring Boot官方推荐的视图层技术) Thymeleaf特点:thymeleaf通过特定的语法对html的标记进行渲染。 Spring Boot整合Thymeleaf 的项目步骤 创建Thymeleaf的项目(maven project的jar类型的spring boot项目) 打开pom.xml文件,添加启动器坐标 代码: org.springframework.boot spring-boot-starter-parent 2.2.4.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-thymeleaf 编写Controller控制器 代码: @Controller public class UserController { /** * 返回一个String的返回值(恒跳转),并且不是一个异步的ResponseBoby响应 * 框架会自动在templates目录下查找与之对应的html页面, * 由Thymeleaf渲染出来。 * 前缀:classpath:/templates 后缀:.html * 如果想要跳转到控制器,必须要让前缀和后缀失效,加上forward或redirect */ @RequestMapping("/show") public String showInfo(Model model) { //存储用户名字符串,显示到页面 model.addAttribute("username","翠花"); //前缀:classpath:/templates 后缀:.html return "index"; } } 编写Thymeleaf视图层页面 (负责数据的展示) Thymeleaf页面必须要放在src/main/resources/templates下 templates:该目录是安全.意味着目录下的内容不允许外界直接访问。 启动类 浏览器输入: localhost:8080/show Thymeleaf 语法详解 变量输出 th:text :在页面中输出值 th:value : 将值放入input标签的value属性中 用户名:
用户名: Thymeleaf内置对象 (内置对象一定用#) 1:字符串操作 strings strings.isEmpty() : 判断字符串是否为空。True,false strings.startsWith() : 判断字符串是否已什么开头。True,false strings.endsWith() : 判断字符串是否已什么结尾。True,false strings.length() : 返回字符串的长度 strings.indexOf() : 查找子字符串出现的位置 strings.toUpperCase():转大写 strings.tolowerCase():转小写 Strings.substring() :截取子字符串 用户名的长度:
获取用户名的姓: 日期格式化处理 dates dates.format():默认以浏览器作为格式化标签 dates.format(time,’yyyy-MM-dd hh:mm:ss ’): 按照自定义的格式进行转换 dates.year():获取年 dates.month():获取月 dates.day():获取日 当前时间:
格式化日期: 条件判断 1:th: if controller: model.addAttribute("sex", "男"); html: 您可能喜欢:篮球,动漫 th:switch th:case 循环迭代遍历 th:each 1:迭代遍历list
序号 编号 姓名 年龄
2:迭代遍历map ... 作用域的对象数据的获取操作 //作用域 request,session application request.setAttribute("req", "HttpServletRequest"); request.getSession().setAttribute("sess", "HttpSession"); request.getSession().getServletContext().setAttribute("app", "ServletContext"); Request数据:
Session数据:
Application数据:
Url表达式 th:href th:src th:action 1:表达式语法 @{} 2: 路径类型 绝对路径 相对路径 1:相对于当前项目的根目录 / 2: 相对于服务器路径的根目录 ~ 百度一下 百度一下 show

/template/Home/Zkeys/PC/Static