我正在为 future 的应用程序评估 Spring Boot,并希望使用 Groovy 模板来获得其纯粹的可读性。不幸的是,我在遍历要添加到从 Controller 返回的 ModelAndView 对象的对象列表时遇到了问题。
这是我的 Controller :
@RestController
@RequestMapping("/ships")
public class ShipsController {
@Autowired
ShipDao shipDao;
@RequestMapping(method = RequestMethod.GET)
public ModelAndView ships() {
final ModelAndView modelAndView = new ModelAndView("views/ships");
modelAndView.addObject("ships", this.shipDao.findAll());
return modelAndView;
}
}
这是我的模板:
yieldUnescaped '<!DOCTYPE html>'
html(lang:'en') {
head {
meta('http-equiv':'"Content-Type" content="text/html; charset=utf-8"')
title('My page')
}
body {
p('Look at all these ships:')
ul {
ships.each { ship ->
li('$ship.name')
}
}
}
}
但我在浏览器中看到的是:
Look at all these ships:
$ship.name
我能够确定从 DAO 返回的列表包含三个实体,但这似乎被模板忽略/未识别。
同样让我感到奇怪的是,即使 ships 没有出现在模板中,为什么它甚至显示一个 li 元素?在那种情况下(空列表)我本以为没有,或者更确切地说是引用空对象的错误。
有人有想法吗?
编辑
我刚刚对 Thymeleaf 模板进行了同样的尝试,效果非常好。因此它不是我的 Controller 。
难道您只能将 Groovy 模板用于 Groovy 而不能用于 Java?
最佳答案
我在使用 groovy 模板时遇到了同样的问题。看起来 groovy 模板引擎将您的模板代码包装到一个以模板文件命名的临时类中。在您的情况下,它创建名为 ships
的类并且该类名隐藏了您的模型属性。所以,ships.each{...}
尝试迭代 Class<ships>
类型的实例.
您可以重命名模型属性或使用 spring 的隐式 RequestContext 属性,如 spring.model.ships.each{...}
关于java - Spring Boot 与 Groovy 模板——无法迭代 ModelAndView 中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30695477/