将日期绑定到 Grails 中的命令对象 [英] bind date to command object in Grails

查看:15
本文介绍了将日期绑定到 Grails 中的命令对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我提交了一个日期(作为字符串).我想将它映射到一个命令对象.我环顾四周,没有找到关于如何在命令对象中进行映射到真实日期的好资源.

I have a date (as a string) being submitted. I'd like to map this to a command object. I have looked around quite a bit and found no great resource on how to do this mapping within a command object to a real date.

如果我要在控制器本身中执行此操作,我可以执行以下操作,但是这不允许我轻松映射到我的命令对象中.

If I were to do this in the controller itself I could just do the following, however this doesn't allow me to easily map into my command object.

def endDate = params.date('endDate', 'MM/dd/yyyy')

对于我的命令对象,我能够得到的最接近的是覆盖日期对象的 getter 和 setter.两者都需要被覆盖,否则不使用 setter.这是我第一次尝试的(将字符串设置为日期,但获取日期).所以这不使用setter:

For my command object, the closest I've been able to get is to override the getter and setter for the date object. Both need to be overridden or else the setter is not used. This is what I first tried (set the String to Date, but get the Date). So this doesn't use the setter:

@grails.validation.Validateable
class TaskCreateCommand {

    Date startDate


    public void setStartDate(String dateStr){
        this.start = Date.parse('MM/dd/yyyy', dateStr)
    }

}

这不会产生任何运行时问题,但没用,因为我无法提取实际的 Date 对象.

This doesn't give any runtime problems, but is useless because I can't pull out the actual Date object.

@grails.validation.Validateable
class TaskCreateCommand {

    Date startDate


    public void setStartDate(String dateStr){
        this.start = Date.parse('MM/dd/yyyy', dateStr)
    }

    public String getStartDate(){
        return start.toString()
    }
}

推荐答案

巧合的是我今天也在看同样的问题,于是关注了 这个来自@Don的回答.我能够将日期正确绑定到命令对象.

Co-incidentally I was looking at the same problem today, and followed this answer from @Don. I was able to bind a date properly to the command object.

@Validateable
class BookCommand {
    String name
    Date pubDate
    Integer pages
}

//Controller
def index(BookCommand cmd) {
        println cmd.name
        println cmd.pages
        println cmd.pubDate

        render "Done"
    }

//src/groovy
class CustomDateEditorRegistrar implements PropertyEditorRegistrar {
    public void registerCustomEditors(PropertyEditorRegistry registry) {
        String dateFormat = 'yyyy/MM/dd'
        registry.registerCustomEditor(Date, new CustomDateEditor(new SimpleDateFormat(dateFormat), true))
    }
}

//URL
http://localhost:8080/poc_commandObject/book?name=Test&pages=10&pubDate=2012/11/11

//Println
Test
10
Sun Nov 11 00:00:00 EST 2012

这篇关于将日期绑定到 Grails 中的命令对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆