首页 > 解决方案 > Mustache 不适用于 @RestController 但适用于 @Controller

问题描述

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

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

当我运行上面的代码并访问 localhost 时,我得到了字符串“index”打印在上面,没有别的。但是,当我更改@RestController@Controllerlocalhost 时,会按预期显示网站。

不能@RestContoller和 Mustache 一起使用吗?

标签: spring-bootmustache

解决方案


@RestController基本上是@Controllerand @ResponseBody,这意味着您返回的 "index" 正在被评估为实际的字符串。

所以不,使用 Mustache 和 没有问题@RestController,但会@RestController返回响应正文(不是视图)。

为了解决这个问题,您可以将其更改为纯文本@Controller,对于返回 JSON 的类的其他方法,将@ResponseBody注释添加到方法中。


推荐阅读