Spring Boot集成FreeMarker 时访问不到.ftl文件

Spring Boot 项目集成 FreeMarker时,未进行正确配置的话会出现404错误,如图所示:
在这里插入图片描述

Spring Boot 要集成 FreeMarker 模板引擎时必须经过正确的配置,大致可分为5 个步骤:

  1. 引入依赖
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
 </dependency>
  1. 在application.yml文件中进行如下配置,务必配置正确(.properties文件也一样)
  freemarker:
    template-loader-path: classpath:/templates  # classpath:  一定不能漏写
    cache: false
    charset: UTF-8
    check-template-location: true
    content-type: text/html
    expose-request-attributes: false
    expose-session-attributes: false
    request-context-attribute: req
    suffix: .ftl

曾经因为漏写 classpath: ,花了1个小时找不到原因

  1. 编写controller类
@Controller
@RequestMapping("/")
public class OrderController {

    @GetMapping("/list")
    public ModelAndView list(Map<String, Object> map) {
        map.put("name", "chenf24k");
        return new ModelAndView("name", map);
    }
}
  1. 在Spring Boot项目的resources/templates下新建 name.ftl模板文件
<h1>FreeMarker</h1>
<h2>${name}</h2>
  1. 启动Spring Boot 项目后浏览器输入地址: http://127.0.0.1:8080/list 进行访问
    在这里插入图片描述
发布了18 篇原创文章 · 获赞 6 · 访问量 3228

猜你喜欢

转载自blog.csdn.net/asd0654123/article/details/104725796