在springboot项目中如果要使用动态页面就需要使用到模版引掣,目前比较常用的引掣有:JSP、Velocity、Freemarker、Thymeleaf 而在springboot中推荐使用Thymeleaf ,其语法更简单,功能更强大。下面内容是介绍如何使用Thymeleaf
1.引入Thymeleaf
idea中thymeleaf的导入比较简单,将thymeleaf依赖加入到pom.xml文件中即可实现
找到Spring官方文档:“https://docs.spring.io/spring-boot/docs/2.1.6.RELEASE/reference/htmlsingle/#using-boot-starter”
找到相对应thymeleaf配置文件pom配置信息,并将thymeleaf相关信息配置到应用的pom.xml中
2.Thymeleaf使用
只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;
使用:
1)编写Controller请求 方法success()
package com.atguigu.springboot.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
Logger logger =LoggerFactory.getLogger(getClass());
@RequestMapping("/success")
public String success(){
//classpath:/templates/success.html
return "success";//返回字符串用于找到对应的success.html
}
}
2)页面中导入thymeleaf的名称空间
html lang="en" xmlns:th="http://www.thymeleaf.org">
Title
成功!!!!
3)启动应用进行访问
自动跳转到了对应的页面
3.使用thymeleaf语法
1)在方法中写入需要传到前台的参数
//查出一些数据在页面展示
@RequestMapping("/success")
public String success(Map map){
map.put("hello","你好");
//classpath:/templates/success.html
return "success";
}
2)页面中展示后台所传值
Title
成功!!!!
3)重启应用访问



