Spring Boot整合Thymeleaf及常见小错误

Spring Boot整合Thymeleaf

Thymeleaf 是目前较为流行的视图层技术,Spring Boot 官方推荐使用 Thymeleaf。

什么是Thymeleaf

Thymeleaf是一个支持原生THML 文件的Java 模版,可以实现前后端分离的交互方式,即视图与业务数据分开响应,它可以直接将服务端返回的数据生成 HTML 文件,同时也可以处理 XML、JavaScript、CSS 等格式。
Thymeleaf 最大的特点是既可以直接在浏览器打开 (静态方式),也可以结合服务端将业务数据填充到 HTML之后动态生成的页面(动态方法),Spring Boot 支持Thymeleaf,使用起来非常方便。

1、创建 Maven 工程,不需要创建 Web 工程

  • pom文件的依赖导入
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>springbootthymeleaf</artifactId>
    <version>1.0-SNAPSHOT</version>


    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.2.4.RELEASE</version>
    </parent>

    <dependencies>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        
    </dependencies>
</project>
①、在resources文件夹里新建(application.yml)
server:
  port: 8080
spring:
  thymeleaf:
    prefix: classpath:/templates/   #模版路径
    suffix: .html                   #模版后缀
    servlet:
      content-type: text/html        #设置 Content-type
    encoding: UTF-8                 #编码方式
    mode: HTML5                     #校验 H5格式
    cache: false                    #关闭缓存,在开发过程中可以立即看到页面修改的结果


②、在java目录下新建自己的工程,在工程下创建Application
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

③、创建controller
@Controller
@RequestMapping
public class HelloHandler {

        @GetMapping("/index")
        public ModelAndView index(){
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("index");
            modelAndView.addObject("name","阿泽");
            return modelAndView;
        }
}
④、创建html

引入不要加否则没有代码提示

<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Indexx</h1>
<p th:text="${name}">Hello world!</p>
</body>
</html>

如果需要加载后台返回的业务数据,

则需要在 HTML页面中使用 Thymeleaf 模版标签来完成

1、需要引入模版标签。

<html xmIns:th="http://www.thymeleaf .org">

2、通过特定的标签完成操作。

<p th:text="${name}">Hello World</p>

Thymeleaf 模版标签不同于JSTL,Thymeleaf 模版标签是直接嵌入到 HTML原生标签内部

Thymeleaf常用标签

  • th:text

    用于文本的显示,将业务数据的值填充到HTML标签中。

  • th:if

    用于条件判断,对业务数据的值进行判断,如果条件成立,则显示内容。

    如下演示:

 @GetMapping("/if")
        public ModelAndView ifTest(){
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("text");
            modelAndView.addObject("score",85);
            return modelAndView;
<p th:if="${score>=90}">优秀</p>
<p th:if="${score<90}">良好</p>
  • th:unless

    也用于条件判断,对业务数据的值进行判断,如果条件不成立,则显示内容。

@GetMapping("/unless")
        public ModelAndView unlessTest(){
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("text");
            modelAndView.addObject("score",85);
            return modelAndView;
<p th:unless="${score>=90}">优秀</p>
<p th:unless="${score<90}">良好</p>
  • th:switch 和 th:case

    相当于java中的Switch和case

 @GetMapping("/switch")
    public ModelAndView swithTest() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("text");
        modelAndView.addObject("studentId", 1);
        return modelAndView;

    }
<!-- switch -->
<div th:switch="${studentId}">
    <p th:case="1">张三</p>
    <p th:case="2">李四</p>
    <p th:case="3">王五</p>
  • th:action

    用来指定请求的 URL,相当于form 表单中的action 属性

<form th:action="@{/hello/login}” method="post">
       <input type="submit"/>
</form>
@GetMapping("/redirect/{url}")
public String redirect(@PathVariable("url") String url, Model model){
    (model.addAttribute("url""/hello/login");
     return url;
     }
<form th:action="{url}" method="post">
    <input type="submit"/>
</form>

如果 action 的值直接写在 HTML 中,则需要使用 @{},如果是从后台传来的数据,则使用${}。

  • th:each

    用来遍历的

		<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
  • 用来遍历集合

    1.实体类

    import lombok.AllArgsConstructor;
    import lombok.Data;
    
    @Data
    @AllArgsConstructor
    public class User {
        private  String  name;
        private  Integer id;
    }
    

    2.Contorller

    @GetMapping("/each")
    public ModelAndView each(){
        List<User> users = Arrays.asList(new User("张三",1),new User("李四",2),new User("王五",3));
        ModelAndView modelAndView =new ModelAndView();
        modelAndView.setViewName("test");
        modelAndView.addObject("list",users);
        return modelAndView;
    }
    

    3.视图

    <!--each-->
        <table>
            <tr>
                <th> 编号</th>
                <th> 姓名</th>
            </tr>
            <tr th:each="user:${list}">
                <td th:text="${user.id}"></td>
                <td th:text="${user.name}"></td>
            </tr>
        </table>
    
  • th:value

    用来给标签赋值

    @GetMapping("/value")
    public ModelAndView value(){
        ModelAndView modelAndView =new ModelAndView();
        modelAndView.setViewName("test");
        modelAndView.addObject("list","sprngboot");
        return modelAndView;
    }
    
    <!--value-->
            <input type="text" th:value="${list}">
    
  • th:href

    用来设置超链接的href

    @GetMapping("/href")
    public ModelAndView href(){
        ModelAndView modelAndView =new ModelAndView();
        modelAndView.setViewName("test");
        modelAndView.addObject("src","https://www.baidu.com");
        return modelAndView;
    }
    
    <!--href-->
        <a th:href="${src}">百度</a>
    
  • th:selected标签

    给html设置选中的元素,条件成立选中,条件不成立不选中

@GetMapping("/selected")
public ModelAndView selected(){
    List<User> users = Arrays.asList(new User("张三",1),new User("李四",2),new User("王五",3));
    ModelAndView modelAndView =new ModelAndView();
    modelAndView.setViewName("test");
    modelAndView.addObject("list",users);
    modelAndView.addObject("name","李四");
    return modelAndView;
}
<!--selected-->
        <select>
            <option
                    th:each="user:${list}"
                    th:value="${user.id}"
                    th:text="${user.name}"
                    th:selected="${user.name==name}"
            ></option>
        </select>

结合th:each来使用,首次遍历list的集合来动态的创建元素,更具每次遍历出的user、name于业务数据中的name是否相等来决定是否要选择。

  • th:attr

    给HTML的任意标签来赋值

    @GetMapping("/attr")
    public ModelAndView attr(){
        ModelAndView modelAndView =new ModelAndView();
        modelAndView.setViewName("test");
        modelAndView.addObject("attr","spring boot");
        return modelAndView;
    }
    
    <!--attr-->
            <input th:attr="value=${attr}"><br>
            <input th:value="${attr}">
    

Spring Boot 项目运行时报错

报错如下:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sQdhE3EF-1681149238808)(C:\Users\lrz99\AppData\Roaming\Typora\typora-user-images\image-20230322095546486.png)]

Error starting ApplicationContext. To display the conditions report re-run your application with ‘debug’ enabled.

一行的大概意思是:

启动ApplicationContext时出错。要显示条件报告,请在启用“调试”的情况下重新运行您的应用程序。

== 主要看下面的错误 ==

Description:

Failed to bind properties under ‘spring.thymeleaf.servlet’ to org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties$Servlet:

Reason: No converter found capable of converting from type [java.lang.String] to type [org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties$Servlet]

是以为配置的的application.yml里面项出错了,注意空格

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值