Spring Boot如何整合FreeMarker模板引擎

作者:StrongerBrother 时间:2022-09-06 15:49:32 

POM


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

项目结构


src/
+- main/
  +- java/
  |  +- com
  |    +- controller/
  |    |  +- IndexController.class
  |    +- Application.class
  +- resources/
    +- templates/
      +- index.ftlh
  • Application为应用程序启动类

  • IndexController为控制器,里面含有一个index请求处理方法,它返回index字符串,表示渲染模板文件index.ftlh。

  • index.ftlh为freemarker模板文件

Applciation.class


@SpringBootApplication
public class Application {

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

IndexController.class


@Controller
public class IndexController {
 @GetMapping("/index")
 public String index(Model model) {
   model.addAttribute("name", "Alice");
   return "index";
 }
}

注意@ResponseBody注解不能和freemarker一起使用,所以此处不能标注@RestController注解。

index.ftlh


<!DOCTYPE html>
<html>
<head>
 <title>test</title>
</head>
<body>
hello ${name}!
</body>
</html>

运行

运行Application类里的main方法。

然后访问localhost:8080/index,结果展示为:

hello Alice!

来源:https://www.cnblogs.com/stronger-brother/p/12124784.html

标签:Spring,Boot,FreeMarker,模板,引擎
0
投稿

猜你喜欢

  • java必学必会之线程(2)

    2023-11-09 10:22:35
  • 如何使用Spring AOP的通知类型及创建通知

    2022-03-19 19:32:51
  • flutter窗口初始和绘制流程详析

    2023-08-17 21:07:30
  • Java裁剪压缩PNG图片,透明背景色变黑的解决方案

    2023-11-25 13:21:27
  • Java 高并发三:Java内存模型和线程安全详解

    2021-10-24 07:04:13
  • Springboot自带定时任务实现动态配置Cron参数方式

    2023-11-10 10:21:31
  • SpringBoot 利用thymeleaf自定义错误页面

    2023-11-29 08:29:55
  • Java值传递之swap()方法不能交换的解决

    2023-11-12 20:54:50
  • JAVA抽象类,接口,内部类详解

    2023-11-09 16:37:25
  • 基于C语言实现井字棋游戏

    2023-06-28 21:23:18
  • Java8 CompletableFuture 异步多线程的实现

    2023-07-21 08:07:15
  • Spring之spring-context-indexer依赖详解

    2023-11-23 12:21:41
  • springboot整合mybatis实现数据库的更新批处理方式

    2023-11-29 07:08:37
  • Spring启动过程中实例化部分代码的分析之Bean的推断构造方法

    2022-08-26 02:00:07
  • spring springMVC中常用注解解析

    2023-09-14 20:45:46
  • Java 根据网址查询DNS/IP地址的方法

    2023-06-21 15:31:54
  • SpringBoot整合freemarker实现代码生成器

    2023-07-17 20:31:08
  • Spring运行时动态注册bean的方法

    2023-11-25 04:16:58
  • AndroidStduio3.0 使用gradle将module打包jar文件的方法

    2023-07-01 06:57:20
  • Mybatis RowBounds 限制查询条数的实现代码

    2022-11-18 17:26:03
  • asp之家 软件编程 m.aspxhome.com