SpringBoot 学习系列(七) - 与Thymeleaf结合使用

Springboot默认使用thymeleaf模板引擎

配置与使用

1.在application.properties文件中增加Thymeleaf模板的配置。(这一步也可以不做配置)

#thymelea模板配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**

说明一下,这些配置不是必须的,如果配置了会覆盖默认的。
在开发时建议将spring.thymeleaf.cache设置为false,否则会有缓存,导致页面没法及时看到更新后的效果。
比如你修改了一个文件,已经update到tomcat,但刷新页面还是之前的页面,就是因为缓存引起的。

2.在pom.xml中添加thymeleaf的依赖(这个步骤可以在生成的时候勾选)

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

3.编写一个测试的Controller,用@Controller,别用@RestController

@RequestMapping(value = "/greeting")
public ModelAndView test(ModelAndView mv) {
    mv.setViewName("/greeting");
    mv.addObject("title","欢迎使用Thymeleaf!");
    return mv;
}

可以看到,Controller与普通的SpringMVC的Controller无异。

4.编写greeting.html,如果有css和js文件,放在静态文件目录下

spring-boot项目静态文件目录:/src/java/resources/static
spring-boot项目模板文件目录:/src/java/resources/templates
所以greeting.html文件在/src/java/resources/templates下。

<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" >
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link th:href="@{/css/1.css}" rel="stylesheet"/>
</head>
<body>
<p th:text="'Hello, ' + ${title}" /><br/>

<script th:src="@{/js/jquery/1.11.0/jquery.js}"></script>
<script>
    $(function(){
       alert("page load finish.");
    });
</script>
</body>
</html>

.运行效果

其它传值方式

可以通过Model传值

controller代码:

    @RequestMapping("/")
    public String index(Model model){
        model.addAttribute("title","This is your message");
        return "index";
    }

index.html代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>主页</title>
</head>
<body class="container">
<br/>
    <p th:text="'Hello, ' + ${title}" /><br/>
<br/><br/>

</body>
</html>

效果图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值