Mustache 不适用于@RestController 但适用于@Controller

Mustache does not work with @RestController but works with @Controller

我的 Spring 引导应用程序中有一个预先存在的 @RestController,我想将其与 Mustache 重用。这是我的示例函数(在 Kotlin 中),它应该与 Mustache -

一起使用
@RestController
class IndexController {

    @GetMapping("/")
    fun index(model: Model): String {
        /*model.addAttribute("title", "Test Time")*/
        model["title"] = "App Test"
        return "index"
    }
}

这是我的小胡子文件 -

<!DOCTYPE HTML>

<html>
    <head>
        <meta charset="UTF-8" />
        <title>{{title}}</title>
        <link rel="stylesheet" type="text/css" href="/css/style.css"/>
    </head>

    <body>
        <h1>{{title}}</h1>
        <h3>Welcome!</h3>
        {{>footer}}
    </body>
</html>

当我运行上面的代码并访问本地主机时,我在上面打印了字符串“index”,没有别的。但是,当我将 @RestController 更改为 @Controller 时,本地主机会按预期显示网站。

是否无法将 @RestContoller 与 Mustache 一起使用?

@RestController 基本上是 @Controller@ResponseBody,这意味着您的“索引”的 return 正在评估为实际字符串。

所以不,使用 Mustache 和 @RestController 没有问题,但是 @RestController return 是响应主体(不是视图)。

为了解决这个问题,您可以将其更改为普通 @Controller,对于 class return JSON 的其他方法,添加 @ResponseBody 方法注释。