Grails的Controller中如何获取Domain模型
问题的提出:
domain模型的定义如下,如何在Controller中取得domain模型的元数据
package application class Bird { static domain=[chinese:"鸟"] String name String gender static constraints = { name(attributes:[chinese:"名称"]) gender(attributes:[chinese:"性别"],inList:["公","母"]) } }
问题的解决:
def birdClass=grailsApplication.getArtefact("Domain","application.Bird") def cps=birdClass.getConstrainedProperties() def classChinese=Bird.domain.chinese def properties=[:] def index = { redirect(action: "list", params: params) } def list = { params.max = Math.min(params.max ? params.int('max') : 10, 100) println cps println "propiety:" birdClass.getProperties().each{ def namePropertiy=it.getName() if(namePropertiy == 'id') { properties[namePropertiy]='编号' }else if(namePropertiy == 'dateCreated') { properties[namePropertiy]='创建时间' }else if(namePropertiy == 'lastUpdated') { properties[namePropertiy]='更新时间' }else if(it.isPersistent()==true && cps[namePropertiy]!=null && namePropertiy!='version'){ properties[namePropertiy]=cps[namePropertiy].attributes.chinese?:namePropertiy }else{ println "SHIT:"+namePropertiy } } println classChinese println properties [birdInstanceList: Bird.list(params), birdInstanceTotal: Bird.count(),classChinese:classChinese,properties:properties] }
- <g:set var="entityName" value="${classChinese}" />
- <div class="list">
- <table>
- <thead>
- <tr>
- <g:sortableColumn property="id" title="${properties.id}" />
- <g:sortableColumn property="name" title="${properties.name}" />
- <g:sortableColumn property="gender" title="${properties.gender}" />
- </tr>
最终效果:
心得体会:
做这件事情的最初想法是希望将ConventionOverConfiguration的思想贯彻的更彻底些,将中文化的工作直接“注入”到Grails Scaffolding的过程中,但由于Scaffolding过程中加载的Domain类并非最终类,因此无法正常读取相关元数据,因此最终采用Controller读取数据,通过预先约定好的数据传递给Views的方法,终于把这个“鸟”问题的解决方案整了一个思路出来。
后续还需要完善的地方:
- 类关系处理(1:M, M:1, M:N)
- 通过Controller继承的方式将取Domain类元数据过程“隐藏”
相关推荐
liuttorrie 2020-07-04
Yakamoz 2020-06-17
Lophole 2020-06-13
liaoxuewu 2020-06-11
技术之博大精深 2020-06-10
Lophole 2020-05-25
gtsjx 2020-05-19
Lophole 2020-05-09
SIMONDOMAIN 2020-05-09
书虫媛 2020-05-03
Lophole 2020-04-29
luvhl 2020-04-10
书虫媛 2020-03-07
Lophole 2020-03-03
SIMONDOMAIN 2020-02-25
SIMONDOMAIN 2020-02-19
zhuakuang0 2020-02-17