学无先后,达者为师

网站首页 编程语言 正文

springboot 视图集成

作者:龙兄你好呀 更新时间: 2022-07-09 编程语言

一、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,看到如下页面:
在这里插入图片描述

原文链接:https://blog.csdn.net/rqt1013_/article/details/125658725

栏目分类
最近更新