springboot 视图集成

本文详细介绍了如何在SpringBoot项目中集成和配置Freemarker与Thymeleaf模板引擎,包括引入依赖、自定义配置、创建视图以及在Controller中使用模型数据。通过示例展示了如何展示Hello SpringBoot页面,帮助开发者快速理解和应用这两种模板技术。
摘要由CSDN通过智能技术生成

一、freemarker

SpringBoot内部支持Freemarker视图技术的集成,并提供了自动化配置类FreeMarkerAutoConfiguration,借助自动化配置可以很方便的集成Freemarker基础到 SpringBoot环境中。

1.引入依赖
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2.查找配置类

在idea上双击shift搜索FreeMarkerProperties
在这里插入图片描述
可以看到,freemareker默认加载路径是类路径下一个叫templates的文件夹,并且后缀默认为.ftlh

3.更换配置

如果我们不想用springboot的默认配置,那么可以在application.yml文件中修改这些配置。

spring:
  freemarker:
    #加载路径
    template-loader-path: classpath:/view/
    ##后缀
    suffix: .ftl
    ##字符
    charset: UTF-8
4.访问视图

在resources目录下新建目录views,同时新建一个以后缀.ftl结尾的文件:

<h1>牛马</h1>
<h2>${msg}</h2>

在controller层编写方法,访问视图:

 @RequestMapping("index")
    public String index(Model model) {
        model.addAttribute("msg", "hello springboot");
        return "index";
    }

浏览器输入http://localhost:8080/index,看到如下页面:
在这里插入图片描述

二、thymeleaf

1.引入依赖
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.查找配置类

在idea上双击shift搜索ThymeleafProperties
在这里插入图片描述

可以看到,thymeleaf默认加载路径是类路径下一个叫templates的文件夹,并且后缀默认为.html

3.更换配置

如果我们不想用springboot的默认配置,那么可以在application.yml文件中修改这些配置。

spring:
  thymeleaf:
    # 加载路径
    prefix: classpath:/views/
    suffix: .html
4.访问视图

在resources目录下新建目录views,同时新建一个以后缀.html结尾的文件:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 th:text="${msg}"></h1>
</body>
</html>

在controller层编写方法,访问视图:

 @RequestMapping("index")
    public String index(Model model) {
        model.addAttribute("msg", "hello springboot");
        return "index";
    }

浏览器输入http://localhost:8080/index,看到如下页面:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值