springboot2+freemarker简单使用

时间:2021-12-22 12:14:50

一、src/main/resources/templates下新建welcome.ftl

<!DOCTYPE html>

<html lang="en">

<body>
Date: ${time?date}
<br>
Time: ${time?time}
<br>
Message: ${message}
</body> </html>

二、启动类

package com.my.bootdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Bootdemo1Application { public static void main(String[] args) {
SpringApplication.run(Bootdemo1Application.class, args);
}
}

三、controller

package com.my.bootdemo;

import java.util.Date;
import java.util.Map; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping; @Controller
public class HelloController { @GetMapping("/")
public String welcome(Map<String, Object> model) {
model.put("time", new Date());
model.put("message", "yes, this is message.");
return "welcome";
}
}

四、pom.xml中添加配置

<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>

以上就是全部的配置了,application.properties中不需要任何参数,全部都是默认,启动程序,浏览器输入:http://localhost:8080/

springboot2+freemarker简单使用

整个过程还是比较简单的,但由于我们项目还在使用struts2,直接要使用springboot,以上操作还是花了些时间,故记录一下,花时间主要原因:最开始Controller使用的注解为@RestController,这就造成始终返回给页面的都是welcome这个单词,而不是welcome这个页面。

@RestController = @Controller + @ResponseBody,加上@ResponseBody注解,返回的是json数据,具体实现原理后续在进行调查

一般配置中应该添加前端控制器在服务器时就进行初始化

spring.mvc.servlet.load-on-startup=1