springboot之thymeleaf模板引擎章节

来源:互联网 发布:装修省钱 知乎 编辑:程序博客网 时间:2024/05/17 04:35

1、根据上章步骤构建web项目;

2、在pom.xml配置文件中添加thymeleaf依赖包

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

3、在application.properties文件中配置thymeleaf的相关信息

spring.thymeleaf.prefix=/templates/

spring.thymeleaf.suffix=.html

spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false

4、编写Controller层

@Controller
public class HelloWorld {

    @RequestMapping("/hello")
    public String helloHtml(HashMap<String,Object> map){
        map.put("user","zhangsan");
        return"pages/index";
    }
}

注:记住一定不要用RestController注解

5、在templates下面新建pages文件夹,并在其下面新建index.html文件

6、index.html文件内容参考如下:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'Hello!, ' + ${user} + '!'" >lisi</p>
</body>
</html>

注:一定要在html页面中引入thymeleaf 标签:<html xmlns:th="http://www.thymeleaf.org">

7、启动springboot类,并访问:http://localhost:8080/hello