代码之家  ›  专栏  ›  技术社区  ›  nils petersohn

从控制器中的参数绑定grails日期

  •  39
  • nils petersohn  · 技术社区  · 15 年前

    为什么通过Grails控制器中的参数从视图中提取日期如此困难?

    我不想这样手工提取日期:

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

    我只想用 instance.properties = params .

    在模型中,类型为 java.util.Date 在参数中是所有信息: [dateX_month: 'value', dateX_day: 'value', ...]

    我在网上搜了搜,没有找到任何关于这个的东西。我希望Grails1.3.0能有所帮助,但仍然是一样的。

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

    6 回复  |  直到 9 年前
        1
  •  84
  •   Dónal    10 年前

    Grails版本>=2.3

    中的设置 Config.groovy 定义将参数绑定到 Date

    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

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

    你的顽固得到了回报,很早在Grail1.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) 通过在中注册以下bean,让Grails知道这个日期编辑器 grails-app/conf/spring/resources.groovy

    beans = {
        customPropertyEditorRegistrar(CustomDateEditorRegistrar)
    }
    

    (3) 现在,当您在名为 foo 格式 yyyy/MM/dd 它将自动绑定到名为 使用:

    myDomainObject.properties = params
    

    new MyDomainClass(params)
    
        2
  •  14
  •   Kumar Sambhav    12 年前

    Grails2.1.1在参数中有新的方法,可以方便地进行空安全解析。

    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')
    

    在文档中找到它 here

        3
  •  11
  •   tgarcia    9 年前

    Grails版本>=3.x

    您可以在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"
    
        4
  •  2
  •   Dónal    15 年前

    你试过使用Grails日期选择器插件吗?

    我有很好的经验 calendar plugin .

    (使用日历插件时)提交日期选择请求时,可以自动将查询参数绑定到要用请求填充的域对象。

    例如。

    new DomainObject(params)
    

    您还可以像这样分析“yyyy/mm/dd”日期字符串…

    new Date().parse("yyyy/MM/dd", "2010/03/18")
    
        5
  •  2
  •   chim    13 年前

    @唐谢谢你的回答。

    这里有一个自定义编辑器的替代选择,它先检查日期时间,然后检查日期格式。

    Groovy,只为Java添加半冒号

    import java.text.DateFormat
    import java.text.ParseException
    import org.springframework.util.StringUtils
    import java.beans.PropertyEditorSupport
    
    class CustomDateTimeEditor extends PropertyEditorSupport {
        private final java.text.DateFormat dateTimeFormat
        private final java.text.DateFormat dateFormat
        private final boolean allowEmpty
    
        public CustomDateTimeEditor(DateFormat dateTimeFormat, DateFormat dateFormat, boolean allowEmpty) {
            this.dateTimeFormat = dateTimeFormat
            this.dateFormat = dateFormat
            this.allowEmpty = allowEmpty
        }
    
        /**
         * Parse the Date from the given text, using the specified DateFormat.
         */
        public void setAsText(String   text) throws IllegalArgumentException   {
            if (this.allowEmpty && !StringUtils.hasText(text)) {
                // Treat empty String as null value.
                setValue(null)
            }
            else {
                try {
                    setValue(this.dateTimeFormat.parse(text))
                }
                catch (ParseException dtex) {
                    try {
                        setValue(this.dateFormat.parse(text))
                    }
                    catch ( ParseException dex ) {
                        throw new IllegalArgumentException  ("Could not parse date: " + dex.getMessage() + " " + dtex.getMessage() )
                    }
                }
            }
        }
    
        /**
         * Format the Date as String, using the specified DateFormat.
         */
        public String   getAsText() {
            Date   value = (Date) getValue()
            return (value != null ? this.dateFormat.format(value) : "")
        }
    }
    
        6
  •  1
  •   mpccolorado    10 年前

    Grails版本>=2.3

    本地感知的 将字符串转换为日期的版本

    在SRC/Groovy中:

    package test
    
    import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest
    import org.grails.databinding.converters.ValueConverter
    import org.springframework.context.MessageSource
    import org.springframework.web.servlet.LocaleResolver
    
    import javax.servlet.http.HttpServletRequest
    import java.text.SimpleDateFormat
    
    class StringToDateConverter implements ValueConverter {
        MessageSource messageSource
        LocaleResolver localeResolver
    
        @Override
        boolean canConvert(Object value) {
            return value instanceof String
        }
    
        @Override
        Object convert(Object value) {
            String format = messageSource.getMessage('default.date.format', null, "dd/MM/yyyy", getLocale())
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format)
            return simpleDateFormat.parse(value)
        }
    
        @Override
        Class<?> getTargetType() {
            return Date.class
        }
    
        protected Locale getLocale() {
            def locale
            def request = GrailsWebRequest.lookup()?.currentRequest
            if(request instanceof HttpServletRequest) {
                locale = localeResolver?.resolveLocale(request)
            }
            if(locale == null) {
                locale = Locale.default
            }
            return locale
        }
    }
    

    在conf/spring/resources.groovy中:

    beans = {
        defaultDateConverter(StringToDateConverter){
            messageSource = ref('messageSource')
            localeResolver = ref('localeResolver')
        }
    }
    

    bean的名称“default date converter”非常重要(要覆盖默认的日期转换器)