- 浏览: 25770 次
- 性别:
- 来自: 广州
最新评论
Register multiple date format for binding properities
- 博客分类:
- grails
Grails可以自动把params里面的参数绑定到domain class。有些时候为了能够绑定自定义的日期格式,例如"yyyy-MM-dd",需要register一个自己的CustomDateEditor。
有时候还有需求要绑定多种格式的日期,例如"yyyy/MM/dd"、"yyyy-MM-dd HH:mm:ss"等等,这时候就需要一个支持多种日期格式的CustomDateEditor,解决方法如下:
1. 新建一个MultipleDateEditor.groovy
2. 新建MultipleDateEditorRegistrar.groovy
3. 注册到spring beans
Reference: http://forum.springsource.org/showthread.php?78118-Multiple-Date-Formats-in-a-Form
有时候还有需求要绑定多种格式的日期,例如"yyyy/MM/dd"、"yyyy-MM-dd HH:mm:ss"等等,这时候就需要一个支持多种日期格式的CustomDateEditor,解决方法如下:
1. 新建一个MultipleDateEditor.groovy
package com.myapp import java.beans.PropertyEditorSupport; import java.text.ParseException; import java.util.Date; import org.apache.commons.lang.time.DateFormatUtils; import org.apache.commons.lang.time.DateUtils; import org.springframework.util.StringUtils; /** * Property editor for java.util.Date, supporting multiple custom input formats * and custom output formats. This class utilizes DateUtils and * DateFormatUtils of Apache Commons Lang, and has been tested for version 2.4 * but may work with older versions. * * It should be noted that the date input formats should be inserted into the * array based on the length of the string, longest to shortest. * * This is not meant to be used as system PropertyEditor but rather as * locale-specific date editor within custom controller code, parsing * user-entered number strings into Date properties of beans and rendering * them in the UI form. * * In web MVC code, this editor will typically be registered with * binder.registerCustomEditor calls in a custom initBinder method. * * @author jpreston * @see java.beans.PropertyEditorSupport * @see java.util.Date * @see org.apache.commons.lang.time.DateUtils * @see org.apache.commons.lang.time.DateFormatUtils */ public class MultipleDateEditor extends PropertyEditorSupport { /** * The date format used to format a Date into a String */ public final static String DEFAULT_OUTPUT_FORMAT = "dd/mm/yyyy"; /** * The date formats used to parse a String into a Date */ public final static String[] DEFAULT_INPUT_FORMATS = [ "dd/mm/yyyy hh:mm:ss", "dd-mm-yyyy hh:mm:ss", "dd/mm/yy hh:mm:ss", "dd-mm-yy hh:mm:ss", "dd/mm/yyyy", "dd-mm-yyyy", "dd/mm/yy", "dd-mm-yy" ]; /** The format used to convert a Date into a String */ private String outputFormat; /** An array of date formats used to convert a String into a Date */ private String[] inputFormats; /** Allow empty strings to be parsed instead of treated as null */ private boolean allowEmpty; /** * Create a new MultipleDateEditor instance using the default values */ public MultipleDateEditor() { outputFormat = MultipleDateEditor.DEFAULT_OUTPUT_FORMAT; inputFormats = MultipleDateEditor.DEFAULT_INPUT_FORMATS; allowEmpty = false; } /** * Create a new MultipleDateEditor instance using the given date * input and output formats. * * The "allowEmpty" parameter states if an empty String should be allowed for * parsing, i.e. get interpreted as null value. Otherwise, an * IllegalArgumentException gets thrown in that case. * * @param outputFormat The format used to convert a Date into a String * @param inputFormats An array of date formats used to convert a String into a Date */ public MultipleDateEditor(String outputFormat, String[] inputFormats) { this.outputFormat = outputFormat; this.inputFormats = inputFormats; allowEmpty = false; } /** * Create a new MultipleDateEditor instance using the given date * input and output formats. * * The "allowEmpty" parameter states if an empty String should be allowed for * parsing, i.e. get interpreted as null value. Otherwise, an * IllegalArgumentException gets thrown in that case. * * @param outputFormat The format used to convert a Date into a String * @param inputFormats An array of date formats used to convert a String into a Date * @param allowEmpty Allow empty strings to be parsed instead of treated as null */ public MultipleDateEditor(String outputFormat, String[] inputFormats, boolean allowEmpty) { this.outputFormat = outputFormat; this.inputFormats = inputFormats; this.allowEmpty = allowEmpty; } /** * Format the Date as String, using the specified outputFormat. * * If allowEmpty is true (default is false), and the Date is null, an empty * String will be returned; otherwise it is possible that a NPE or other * parsing exception will occur. * * @return The string value of the Date */ @Override public String getAsText() { if (allowEmpty && getValue() == null) { return ""; } return DateFormatUtils.format((Date) getValue(), outputFormat); } /** * Parse the Date from the given text, using the first matching date format * specified in the inputFormats array. * * If no matching input format is found, an IllegalArgumentException is thrown. * * If allowEmpty is true (default is false), and the String is null, the Date * will be interpreted as null; otherwise an IllegalArgumentException is thrown. * * @param text the text to convert into a java.util.Date * @throws IllegalArgumentException thrown if no matching format is found */ @Override public void setAsText(String text) throws IllegalArgumentException { try { if (StringUtils.hasText(text)) { setValue(DateUtils.parseDate(text, inputFormats)); } else { if (allowEmpty) { setValue(null); } else { throw new IllegalArgumentException( "The text specified for parsing is null"); } } } catch (ParseException ex) { throw new IllegalArgumentException("Could not parse text [" + text + "] into any available date input formats", ex); } } /** * If allowEmpty is true (default is false), and the Date is null, an empty * String will be returned; otherwise it is possible that a NPE or other * parsing exception will occur. * * If allowEmpty is true (default is false), and the String is null, the Date * will be interpreted as null; otherwise an IllegalArgumentException is thrown. * * @return whether empty strings are allowed */ public boolean isAllowEmpty() { return allowEmpty; } /** * If allowEmpty is true (default is false), and the Date is null, an empty * String will be returned; otherwise it is possible that a NPE or other * parsing exception will occur. * * If allowEmpty is true (default is false), and the String is null, the Date * will be interpreted as null; otherwise an IllegalArgumentException is thrown. * * @param allowEmpty whether empty strings should be allowed */ public void setAllowEmpty(boolean allowEmpty) { this.allowEmpty = allowEmpty; } /** * Get the date formats used to parse a String into a Date * * @return The date formats used to parse a String into a Date */ public String[] getInputFormats() { return inputFormats; } /** * Set the date formats used to parse a String into a Date. It should be * noted that the date formats should be inserted into the array based * on the length of the format, longest to shortest. * * * @param inputFormats The date formats used to parse a String into a Date */ public void setInputFormats(String[] inputFormats) { this.inputFormats = inputFormats; } /** * Get the format used to convert a Date into a String * * @return The format used to convert a Date into a String */ public String getOutputFormat() { return outputFormat; } /** * Set the format used to convert a Date into a String * * @param outputFormat The format used to convert a Date into a String */ public void setOutputFormat(String outputFormat) { this.outputFormat = outputFormat; } }
2. 新建MultipleDateEditorRegistrar.groovy
package com.myapp import org.springframework.beans.PropertyEditorRegistrar import org.springframework.beans.PropertyEditorRegistry /** * binding date properties with customer format * "yyyy-MM-dd HH:mm:ss" * "yyyy-MM-dd HH:mm" * "yyyy-MM-dd" */ public class MultipleDateEditorRegistrar implements PropertyEditorRegistrar { public void registerCustomEditors(PropertyEditorRegistry registry) { registry.registerCustomEditor(Date.class, new MultipleDateEditor("yyyy-MM-dd HH:mm:ss", ["yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd"] as String[], true)); } }
3. 注册到spring beans
beans = { customPropertyEditorRegistrar(com.nazuche.MultipleDateEditorRegistrar) }
Reference: http://forum.springsource.org/showthread.php?78118-Multiple-Date-Formats-in-a-Form
发表评论
-
Fedora 14 下grails中文乱码问题(解决方法)
2011-10-20 18:25 1170MySQL默认字符编码为latin1,因此用Grails写入数 ... -
Grails - binding a customized date format
2011-09-26 18:26 1313It has been possible to bind a ... -
Changing last login date in Grails with Spring Security
2011-09-06 14:31 1192在使用grails spring security core ... -
Grails, spring-security-core plugin:使用email登录
2011-09-06 14:27 27391. Implement the first requirem ... -
Run a Java web application within grails
2011-08-27 13:22 959Ever needed to run an existing ... -
Execute SQL Scripts in Grails Bootstrap or Integration Tests
2011-08-12 15:45 1716I recently had to execute some ... -
Grails, JQuery, and AJAX
2011-08-11 15:02 1402By now, you’re probably under t ... -
Grails - Logging from a Controller or Service
2011-08-11 14:55 1039Logging informational messages ... -
grails taglib修改datePicker格式
2011-08-10 17:07 1973grails的datePicker标签很好,但是并不能设置成y ... -
grails使用build-test-data插件准备测试数据
2011-08-10 11:30 916什么?!还有专门负责 ... -
Grails, p6spy and Sql Profiler
2011-08-09 23:05 1145There are several ways to have ...
相关推荐
Java Architecture for XML Binding (JAXB) 是Java平台上的一个标准技术,它允许程序开发者将XML文档与Java对象之间进行绑定,实现XML数据的序列化和反序列化。JAXB是Java SE和Java EE环境中的一部分,提供了高效且...
THE Java™Architecture for XML Binding (JAXB) provides a fast and convenient way to bind between XML schemas and Java representations, making it easy for Java developers to incorporate XML data and ...
在C#编程中,`BindingSource`组件是一个非常重要的工具,用于在UI(用户界面)控件和数据源之间建立数据绑定。它提供了一种方便的方式来管理数据的显示、编辑和同步,尤其是在涉及多个控件与同一数据源交互的场景中...
在 WPF 中,`StringFormat` 可以在 `Binding` 对象中设置,以控制绑定到 UI 元素(如 `TextBox`)的数据如何显示。其基本语法类似于 C# 中的 `string.Format` 方法,但使用 `{}` 代替 `{0}` 这样的索引表示。 ### ...
<DataGridTextColumn Header="Publication Date" Binding="{Binding PublicationDate, StringFormat='{}{0:yyyy-MM-dd}'}" /> <Button Content="Add Book" Command="{Binding AddBookCommand}" /> ``` **视图...
在Windows Forms应用开发中,`BindingSource`组件扮演着至关重要的角色,它是连接数据源与UI控件的关键组件。本文将深入探讨`BindingSource`在WinForm开发中的使用,包括其基本概念、功能、以及如何实现主细表绑定、...
win32-ia-32-48_binding.node插件去掉node不报错win32-ia-32-48_binding.node插件去掉node不报错win32-ia-32-48_binding.node插件去掉node不报错win32-ia-32-48_binding.node插件去掉node不报错win32-ia-32-48_...
在这个“WPF的binding代码实例”中,我们将深入探讨几个基础的绑定用法,帮助开发者更好地理解和应用这一特性。 1. **基本绑定语法** WPF中的数据绑定通常使用`{Binding}`标记来实现。例如,一个`TextBlock`控件的...
Port Binding Failed(处理方案).md
2. **创建绑定(Binding)**:接着,为需要绑定的控件属性创建一个`Binding`对象,指定要绑定的数据源属性。 ```csharp myTextBlock.SetBinding(TextBlock.TextProperty, new Binding("MyDataProperty")); ``` ...
标题中的"win32-x64-51-57-59-64-67-72-79-83-binding.node多版本.zip"揭示了这是一份包含多个版本的`binding.node`模块的压缩包。`binding.node`在IT行业中,特别是Node.js的上下文中,是一个关键的概念,它是Node....
Android支持JAXB(Java Architecture for XML Binding) JAXB(Java Architecture for XML Binding)是Java领域中的一项标准技术,能够根据XML Schema生成Java类,并将XML实例文档反向生成Java对象树。JAXB提供了将...
Emacs Key binding for Delphi 7(親測),Delphi xe2(也可以用) 使用方法: 使用delphi安裝MyEmacs組件即可, 每次打開delphi時,需要在Key Mapping中去掉勾選【Buffer List】這個Module即可, 里面有一些我自己的快捷...
Data Binding with Windows Forms 2.0: Programming Smart Client Data Applications with .NET By Brian Noyes ............................................... Publisher: Addison Wesley ...
EFI驱动模型与Windows驱动模型的比较和Driver Binding的实现 本文主要介绍了EFI驱动模型的概念,特别是Driver Binding的实现过程,同时借鉴了Windows驱动模型的一些概念,以便更好地理解EFI驱动模型。 首先,我们...
在Android开发领域,MVVM(Model-View-ViewModel)架构、ViewBinding以及Kotlin语言的组合,已经成为现代应用开发的标准工具和技术栈。本教程将帮助初学者了解这三种技术的基本概念,以及如何将它们整合到实际项目中...
linux-x64-64_binding.node。 node-sass的linux-x64-64_binding.node文件
JAXB,即Java Architecture for XML Binding,是Java EE的一部分,提供了一种将XML数据结构化为Java对象的机制,以及反向的绑定过程。本文将深入探讨JAXB的实现原理、使用方法和最佳实践。 JAXB为Java开发者提供了一...
### Beans Binding:经验和技巧 #### 一、简介 **Beans Binding** 是一项强大的技术,它允许开发者轻松地在 Java 应用程序中的不同组件之间建立数据绑定。这项技术基于 JSR 295(Java Specification Request 295)...