Spring 启动无法解析 Freemarker 视图

Spring Boot unable to resolve Freemarker view

我第一次尝试使用 Spring 引导显示 Freemarker 视图,目前在浏览器中出现以下错误:

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sun Feb 19 17:59:07 GMT 2017 There was an unexpected error (type=Not Found, status=404). No message available

我正在使用 Spring Boot 1.5。

我的文件结构:

登录控制器

package com.crm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.crm.service.LoginService;

@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;

    @RequestMapping("/login")
    public String authenticate() {
        return "loginPage";
    }
}

application.properties

spring.freemarker.template-loader-path: /
spring.freemarker.suffix: .ftl

服务器

package com.crm;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Server{

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

为什么 Spring 无法解析 loginPage.ftl 视图?为什么我在网络浏览器中看不到它?

你在application.properties里面的freemarker模板目录设置是错误的。应该是:

spring.freemarker.template-loader-path=classpath:/templates/

使用 Spring Boot 1.5.1,您不需要将这些属性添加到您的 application.properties 文件中,由于自动配置,它们已经被定义。

删除这 2 个属性,它应该与您的 pom.xml 中的以下依赖项一起使用:

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

可在此处找到文档:http://docs.spring.io/spring-boot/docs/1.5.1.RELEASE/reference/htmlsingle/#boot-features-spring-mvc-template-engines

当我从控制器方法将模板名称作为构造函数参数返回给 ModelAndView 对象而不仅仅是一个字符串时,它开始为我工作。不知道为什么,但我没有时间弄明白,正在寻找快速修复方法。如果有人愿意解释,请做。

Spring 使用 Freemarker 启动 2.0.2.RELEASE。这是application.properties的内容:

spring.freemarker.enabled=true
spring.freemarker.template-loader-path=classpath:/templates

Spring Boot 最近又引入了一个重大变化,这导致了臭名昭著的 whitelabel error 页面。他们将默认后缀从 .ftl 更改为 .ftlh

https://github.com/spring-projects/spring-boot/issues/15131

因此对于 Spring Boot 2.2.x 应用程序,必须更新这些扩展。