Spring Boot整合Thymeleaf视图层

目录
  • Spring Boot整合Thymeleaf
    • Spring Boot整合Thymeleaf 的项目步骤
  • Thymeleaf 语法详解

Spring Boot整合Thymeleaf

Spring Boot整合Thymeleaf(Spring Boot官方推荐的视图层技术)

Thymeleaf特点:thymeleaf通过特定的语法对html的标记进行渲染。

Spring Boot整合Thymeleaf 的项目步骤

  1. 创建Thymeleaf的项目(maven project的jar类型的spring boot项目)
    Spring Boot整合Thymeleaf视图层_第1张图片
  2. 打开pom.xml文件,添加启动器坐标
    Spring Boot整合Thymeleaf视图层_第2张图片
    代码:

    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
        
    
  1. 编写Controller控制器
    Spring Boot整合Thymeleaf视图层_第3张图片

代码:

@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";
	}
}

  1. 编写Thymeleaf视图层页面 (负责数据的展示)
    Thymeleaf页面必须要放在src/main/resources/templates下
    templates:该目录是安全.意味着目录下的内容不允许外界直接访问。
    Spring Boot整合Thymeleaf视图层_第4张图片
  2. 启动类
    Spring Boot整合Thymeleaf视图层_第5张图片
  3. 浏览器输入: localhost:8080/show
    Spring Boot整合Thymeleaf视图层_第6张图片

Thymeleaf 语法详解

  1. 变量输出
    th:text :在页面中输出值
    th:value : 将值放入input标签的value属性中
用户名:

用户名:
  1. 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() :截取子字符串
用户名的长度:  
  
获取用户名的姓:
  1. 日期格式化处理 dates
    dates.format():默认以浏览器作为格式化标签
    dates.format(time,’yyyy-MM-dd hh:mm:ss ’): 按照自定义的格式进行转换
    dates.year():获取年
    dates.month():获取月
    dates.day():获取日
当前时间:
 
格式化日期:
  1. 条件判断
    1:th: if

controller:

model.addAttribute("sex", "男");

html:

您可能喜欢:篮球,动漫 
  1. th:switch
    th:case

  2. 循环迭代遍历

  3. th:each

	1:迭代遍历list
		
序号 编号 姓名 年龄

2:迭代遍历map
...

  1. 作用域的对象数据的获取操作
	//作用域  request,session  application 
request.setAttribute("req", "HttpServletRequest");
request.getSession().setAttribute("sess", "HttpSession");
request.getSession().getServletContext().setAttribute("app", "ServletContext");


Request数据:
Session数据:
Application数据:
  1. Url表达式
    th:href
    th:src
    th:action
    1:表达式语法 @{}
    2: 路径类型
    1. 绝对路径

    2. 相对路径

1:相对于当前项目的根目录  /
      
2: 相对于服务器路径的根目录 ~
      


 百度一下
 百度一下
 show
 

你可能感兴趣的:(Spring Boot整合Thymeleaf视图层)