加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

数据绑定 – 从控制器中的params绑定Grails日期

发布时间:2020-12-14 16:39:36 所属栏目:大数据 来源:网络整理
导读:为什么这么难以从视图中通过grails控制器中的参数提取日期? 我不想像这样用手提取日期: instance.dateX = parseDate(params["dateX_value"])//parseDate is from my helper class 我只想使用instance.properties = params。 在模型中,类型是java.util.Dat
为什么这么难以从视图中通过grails控制器中的参数提取日期?

我不想像这样用手提取日期:

instance.dateX = parseDate(params["dateX_value"])//parseDate is from my helper class

我只想使用instance.properties = params。

在模型中,类型是java.util.Date,在params中是所有的信息:[dateX_month:’value’,dateX_day:’value’,…]

我在网上搜索,并没有发现任何东西。我希望Grails 1.3.0可以帮助,但仍然是同样的事情。

我不能,也不会相信用手提取日期是必要的!

解决方法

Grails版本> = 2.3

Config.groovy中的设置定义了将参数绑定到日期时将用于应用程序的日期格式

grails.databinding.dateFormats = [
        'MMddyyyy','yyyy-MM-dd HH:mm:ss.S',"yyyy-MM-dd'T'hh:mm:ss'Z'"
]

grails.databinding.dateFormats中指定的格式将按照它们包含在列表中的顺序尝试。

您可以使用@BindingFormat覆盖单个命令对象的这些应用程序范围格式

import org.grails.databinding.BindingFormat

class Person { 
    @BindingFormat('MMddyyyy') 
    Date birthDate 
}

Grails版本< 2.3

i can’t and will not belief that extracting the date by hand is nessesary!

你的固执得到回报,自从早在Grails 1.3之前就已经可以绑定一个日期了。步骤是:

(1)创建一个注册了日期格式的编辑器的类

import org.springframework.beans.PropertyEditorRegistrar
import org.springframework.beans.PropertyEditorRegistry
import org.springframework.beans.propertyeditors.CustomDateEditor
import java.text.SimpleDateFormat

public class CustomDateEditorRegistrar implements PropertyEditorRegistrar {

    public void registerCustomEditors(PropertyEditorRegistry registry) {

        String dateFormat = 'yyyy/MM/dd'
        registry.registerCustomEditor(Date,new CustomDateEditor(new SimpleDateFormat(dateFormat),true))
    }
}

(2)通过在grails-app / conf / spring / resources.groovy中注册以下bean,使Grails知道此日期编辑器

beans = {
    customPropertyEditorRegistrar(CustomDateEditorRegistrar)
}

(3)现在,当您以yyyy / MM / dd格式在名为foo的参数中发送日期时,它将自动使用以下两种方式之一绑定到名为foo的属性:

myDomainObject.properties = params

要么

new MyDomainClass(params)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读