nil*_*ohn 40 data-binding grails groovy controller date
为什么通过grails控制器中的参数从视图中提取日期这么难?
我不想像这样用手提取日期:
instance.dateX = parseDate(params["dateX_value"])//parseDate is from my helper class
Run Code Online (Sandbox Code Playgroud)
我只是想用instance.properties = params
.
在模型中,类型是java.util.Date
和params中的所有信息:[dateX_month: 'value', dateX_day: 'value', ...]
我在网上搜索,没有发现任何事情.我希望Grails 1.3.0可以帮助但仍然是相同的.
我不能也不会相信手工提取日期是必要的!
Dón*_*nal 85
一个设置Config.groovy
定义了将params绑定到a时将在应用程序范围内使用的日期格式Date
grails.databinding.dateFormats = [
'MMddyyyy', 'yyyy-MM-dd HH:mm:ss.S', "yyyy-MM-dd'T'hh:mm:ss'Z'"
]
Run Code Online (Sandbox Code Playgroud)
grails.databinding.dateFormats
将按照列表中包含的顺序尝试指定的格式.
您可以使用覆盖单个命令对象的这些应用程序范围格式 @BindingFormat
import org.grails.databinding.BindingFormat
class Person {
@BindingFormat('MMddyyyy')
Date birthDate
}
Run Code Online (Sandbox Code Playgroud)
我不能也不会相信手工提取日期是必要的!
你的固执得到了回报,可以在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))
}
}
Run Code Online (Sandbox Code Playgroud)
(2)通过注册以下bean使Grails知道这个日期编辑器grails-app/conf/spring/resources.groovy
beans = {
customPropertyEditorRegistrar(CustomDateEditorRegistrar)
}
Run Code Online (Sandbox Code Playgroud)
(3)现在,当您foo
在以格式命名的参数中发送日期时,yyyy/MM/dd
它将自动绑定到foo
使用以下任一命名的属性:
myDomainObject.properties = params
Run Code Online (Sandbox Code Playgroud)
要么
new MyDomainClass(params)
Run Code Online (Sandbox Code Playgroud)
Kum*_*hav 14
Grails 2.1.1在params中有一个新方法,可以轻松实现null安全解析.
def val = params.date('myDate', 'dd-MM-yyyy')
// or a list for formats
def val = params.date('myDate', ['yyyy-MM-dd', 'yyyyMMdd', 'yyMMdd'])
// or the format read from messages.properties via the key 'date.myDate.format'
def val = params.date('myDate')
Run Code Online (Sandbox Code Playgroud)
在这里找到doc
tga*_*cia 11
您可以在application.yml中设置遵循以下语法的日期格式:
grails:
databinding:
dateFormats:
- 'dd/MM/yyyy'
- 'dd/MM/yyyy HH:mm:ss'
- 'yyyy-MM-dd HH:mm:ss.S'
- "yyyy-MM-dd'T'hh:mm:ss'Z'"
- "yyyy-MM-dd HH:mm:ss.S z"
- "yyyy-MM-dd'T'HH:mm:ssX"
Run Code Online (Sandbox Code Playgroud)