[英]Can I use a Bean as a model in grails instead of a Map?
Short Question: I'd like to use a typed bean as a model in grails instead of a Map. 简短的问题:我想在Grails中使用类型化的bean作为模型,而不是Map。 Is this possible?
这可能吗?
I'd like to do this: 我想这样做:
def index = {
new Person(firstName:"foo", lastName:"bar", age:30)
}
Instead of this: 代替这个:
def index = {
[firstName:"foo", lastName:"bar", age:30]
}
Long Question: I'm maintinaing a controller written by other developers and it's really difficult to understand all of the possible entries in the model. 长问题:我正在维护一个由其他开发人员编写的控制器,并且很难理解模型中所有可能的条目。 The model is populated over a number of methods.
该模型填充了许多方法。 I'd like to refactor the controller to return a custom bean as the model but I was hoping that the gsp would not need to be changed.
我想重构控制器以返回自定义bean作为模型,但是我希望gsp不需要更改。
I assumed that grails could handle either a map or a bean as a model but soon realised that passing a bean to the gsp resulted in NullPointerExceptions as properties could not be found. 我以为grails可以将地图或bean作为模型来处理,但很快意识到将bean传递给gsp会导致NullPointerExceptions,因为找不到属性。
I realise that my controller can return a map like: 我意识到我的控制器可以返回如下地图:
[model: myBean]
But then I would need to go through the gsp and change all references from ${someProp} to ${model.someProp}. 但是然后,我将需要遍历gsp,并将所有引用从$ {someProp}更改为$ {model.someProp}。
I'm also aware that I can use reflection to convert my bean to a Map but I'd prefer not to do this either. 我也知道我可以使用反射将bean转换为Map,但我也不想这样做。
在控制器的末尾:(请注意,这将返回所有属性)
New Person().properties
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.