Thymeleaf 之 HelloWorld

本文章来自【知识林】

基本每一个知识点的学习都是从HelloWorld开始的,HelloWorld级别的例子只是让人清楚这个知识点的概要及简单的实现流程。

本例子也不例外,通过这个例子对Thymeleaf有个简单的认识,后面逐步深入。

  • Maven依赖

pom.xml文件中需要引入Thymeleaf的依赖配置

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  • 创建核心配置文件

application.properties

server.port=1111

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

注意:

servier.port=1111:指定服务端口为1111,在之前的文章中已经提到过了

spring.thymeleaf.prefix=classpath:/templates/:指定Thymeleaf的页面文件放置的位置(也就是页面文件的前缀),这里的classpath:/templates/指的目录就是src/resources/templates,所以需要创建templates这个目录(默认是没有这个目录的)

spring.thymeleaf.suffix=.html:指定页面文件的后缀,这里配置所有页面文件都是.html的文件。

  • 项目入口类
@SpringBootApplication
public class RootApplication {

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

这个类在之前的文章中随处可见,也没有任何特别之处。

  • 创建MVC控制器
@Controller
public class IndexController {

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index(Model model) {
        model.addAttribute("name", "知识林");
        return "/web/index";
    }
}

注意:

@Controller:只出现在类名上,表示该类为控制器,默认的控制器名称就是类名indexController

@RequestMapping:可出现在类名和方法名上,其value属性指定请求url的地址,method属性指定请求方式,这里是以get方式请求

Model:在参数中的Model是一个数据模型,可通过model.addAttribute方法将数据传递到页面上。这里在model中有一个数据:name=知识林

return "/web/index":指定视图文件,根据application.properties中配置的前缀与后缀可以得出这里的视图文件是:src/resources/templates/web/index.html

  • 创建视图页面文件
<!DOCTYPE html>
<html lang="zh-CN"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">

    <head>
        <title>study01 - helloWorld</title>
    </head>

    <body>
        <h1>Hello : <b th:text="${name}">姓名</b></h1>
    </body>
</html>

注意:

  1. 加入Thymeleaf的命名空间:xmlns:th="http://www.thymeleaf.org"
  2. 显示从控制器传递过来的name值应使用:${name},只是需要在html标签属性中使用;
  3. <b th:text="${name}">姓名</b>:意为将姓名二字替换成控制器传递过来的name对应的值(这里是知识林

如果直接在浏览器里打开这个html文件将显示:

Hello : 姓名

如果在浏览器访问:http://localhost:1111/index ,将显示:

Hello : 知识林

这就是前面所提到的Thymeleaf可以在服务环境和静态环境都能正常运行的例子。

示例代码:https://github.com/zsl131/thymeleaf-study/tree/master/study01

本文章来自【知识林】

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值