java后台

SpringBoot系列—Thymeleaf(五)

2019-08-27  本文已影响0人  海晨忆

个人博客: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>

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

上一篇 下一篇

猜你喜欢

热点阅读