spring-boot - 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
为@Controller
localhost 时,会按预期显示网站。
不能@RestContoller
和 Mustache 一起使用吗?
解决方案
@RestController
基本上是@Controller
and @ResponseBody
,这意味着您返回的 "index" 正在被评估为实际的字符串。
所以不,使用 Mustache 和 没有问题@RestController
,但会@RestController
返回响应正文(不是视图)。
为了解决这个问题,您可以将其更改为纯文本@Controller
,对于返回 JSON 的类的其他方法,将@ResponseBody
注释添加到方法中。
推荐阅读
- amazon-web-services - 为 Lambda 代理集成启用 CORS 支持的问题
- api - 使用 axios 显示来自 Twitter API 的数据
- angular - “MatPaginator”类型上不存在属性“previousPageIndex”
- python - 即使卸载并再次安装,也没有名为 bson 的模块
- go - 无法访问/投射时间。时间
- python - 使用 pymongo 与使用 pandas 进行聚合/分组
- java - 是否可以在搜索之前修复 JTable 相同的问题?
- javascript - node.js 使用 SQS 需要功能示例
- sql - 使用多个选择语句插入私有临时表
- python - 使用模数对数据进行分块的优雅方法?