2、thymeleaf-Springboot环境搭建

1、创建SpringBoot项目

 修改相应的参数

 

 选择web,选择SpringWeb

 

 模板引擎选择Thymeleaf

 

点击下一步之后完成即可

 

完成后会自动帮我们新建很多文件,其中在application.properties中我们需要进行一些配置(有些版本创建时已配置)

# 应用名称
spring.application.name=ch02-web-tpl
# 应用服务 WEB 访问端口
server.port=8080
# THYMELEAF (ThymeleafAutoConfiguration)
# 开启模板缓存(默认值: true )
spring.thymeleaf.cache=true
# 检查模板是否存在,然后再呈现
spring.thymeleaf.check-template=true
# 检查模板位置是否正确(默认值 :true )
spring.thymeleaf.check-template-location=true
#Content-Type 的值(默认值: text/html )
spring.thymeleaf.content-type=text/html
# 开启 MVC Thymeleaf 视图解析(默认值: true )
spring.thymeleaf.enabled=true
# 模板编码
spring.thymeleaf.encoding=UTF-8
# 要被排除在解析之外的视图名称列表,⽤逗号分隔
spring.thymeleaf.excluded-view-names=
# 要运⽤于模板之上的模板模式。另⻅ StandardTemplate-ModeHandlers( 默认值: HTML5)
spring.thymeleaf.mode=HTML5
# 在构建 URL 时添加到视图名称前的前缀(默认值: classpath:/templates/ )
spring.thymeleaf.prefix=classpath:/templates/
# 在构建 URL 时添加到视图名称后的后缀(默认值: .html )
spring.thymeleaf.suffix=.html

 

 

2、在Springboot项目中创建网页

在templates目录当中新建一个html文件(上面的配置中配置了前缀和后缀)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>第一个Springboot的Thymeleaf</title>
</head>
<body>
    <p th:text="${name}"></p><!--th:text用于显示文本,把name的数据显示在标签体内-->
</body>
</html>

 

新建一个controller类用于传递数据到网页中

package com.thymeleaf.ch02webtpl.controller;

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

@Controller
public class HelloController {
    /*
        参数Model 可以存放数据,放入到request作用域当中
        返回值String:表示视图
     */
    @RequestMapping("/hello")   //访问hello这个地址,就会返回index.html
    public String hello(Model model){//这里使用的是Model,就是将数据放到request作用域,亦可以使用HttpServletRequest
        //public String hello(Model model,HttpServletRequest request){
        //添加数据
        model.addAttribute("name","张三");
//        request.addAttribute("name","张三");
        //指定模板视图
        return "index"; //在application中已经设置前缀和后缀,这里只需要提供文件名称即可
    }
}

 

posted @ 2022-06-07 19:37  卓汶  阅读(60)  评论(0编辑  收藏  举报