SpringBoot系列—Thymeleaf(五)

个人博客:haichenyi.com。感谢关注

  SpringBoot官方不推荐使用JSP,因为内嵌Tomcat,Jetty容器不支持以jar的方式运行JSP。SpringBoot中提供了大量模板引擎,包含Freemarker,Mastache,Thymeleaf等。而SpringBoot官方推荐使用Thymeleaf作为模板引擎,因为Thymeleaf提供了完美的SpringMVC的支持。

添加启动器

<!-- thymeleaf 模板启动器 --> 
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

添加模板文件

存放位置

   模板文件,就是我们创建的HTML文件,将创建好的 HTML 页面放到 classpath:/templates/ 目录下, Thymeleaf 就能自动渲染。就是我们的 **resources/templates/**目录。

使用

   自动渲染数据从哪里来呢?跟写APP端的接口差不多,就是少了响应@ResponseBody注解。如下:

package com.haichenyi.springbootwebthymeleaf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {

    /**
     * APP接口
     * @return 返回一个字符串
     */
    @ResponseBody
    @RequestMapping("/hello")
    public String sayHello() {
        return "hello";
    }

    /**
     * 返回模板文件
     * @return 返回名字叫success的HTML页面
     */
    @RequestMapping("/hello1")
    public String sayHello1() {
        return "success";
    }
}

项目结构图如下:

项目结构图.png

   如上所示,当访问 http://localhost:8080/hello的时候,返回的是一个字符串叫hello。当访问
http://localhost:8080/hello1的时候,他会转到我们上面说的templates目录下的success.html页面。

thymeleaf语法使用

HTML中添加命名空间
xmlns:th="http://www.thymeleaf.org"
简单的使用
/**
     * 返回模板文件
     * @return 返回名字叫success的HTML页面
     */
    @RequestMapping("/hello1")
    public String sayHello1(Map<String,Object> map) {
        map.put("name","我是海晨忆");
        return "success";
    }

  还上啊上面的那个方法,添加了一个map参数。这个参数就是返回给success界面的数据存放容器。存放了一个键值对,键是name

  界面怎么使用呢?

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>success模板文件</title>
</head>
<body>
<p>success 模板文件</p>
<p2 th:text="${name}"></p2>
</body>
</html>

  就这样,直接使用这个键即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

海晨忆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值