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

发布于 2024-09-02 08:51:51 字数 411 浏览 7 评论 0原文

为什么通过 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', ...]

我在网上搜索了一下,没有发现任何相关内容。我希望 Grails 1.3.0 能有所帮助,但仍然是同样的事情。

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

Why is it so hard to extract the date from the view via the params in a grails controller?

I don't want to extract the date by hand like this:

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

I just want to use instance.properties = params.

In the model the type is java.util.Date and in the params is all the information: [dateX_month: 'value', dateX_day: 'value', ...]

I searched on the net and found nothing on this. I hoped that Grails 1.3.0 could help but still the same thing.

I can't and will not believe that extracting the date by hand is necessary!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

你的他你的她 2024-09-09 08:51:51

Grails Version >= 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 将按照它们包含在列表中的顺序进行尝试。

覆盖单个命令对象的这些应用程序范围的格式

import org.grails.databinding.BindingFormat

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

您可以使用 @BindingFormat Grails Version 。 2.3

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

你的固执是有回报的,早在 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

beans = {
    customPropertyEditorRegistrar(CustomDateEditorRegistrar)
}

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

myDomainObject.properties = params

new MyDomainClass(params)

Grails Version >= 2.3

A setting in Config.groovy defines the date formats which will be used application-wide when binding params to a Date

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

The formats specified in grails.databinding.dateFormats will be attempted in the order in which they are included in the List.

You can override these application-wide formats for an individual command object using @BindingFormat

import org.grails.databinding.BindingFormat

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

Grails Version < 2.3

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

Your stubbornness is rewarded, it has been possible to bind a date directly since long before Grails 1.3. The steps are:

(1) Create a class that registers an editor for your date format

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) Make Grails aware of this date editor by registering the following bean in grails-app/conf/spring/resources.groovy

beans = {
    customPropertyEditorRegistrar(CustomDateEditorRegistrar)
}

(3) Now when you send a date in a parameter named foo in the format yyyy/MM/dd it will automatically be bound to a property named foo using either:

myDomainObject.properties = params

or

new MyDomainClass(params)
浮世清欢 2024-09-09 08:51:51

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

在文档此处中找到它

Grails 2.1.1 has new method in params for easy null safe parsing.

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

Find it in doc here

§普罗旺斯的薰衣草 2024-09-09 08:51:51

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"

Grails Version >= 3.x

You can set in application.yml the date formats following this syntax:

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"
数理化全能战士 2024-09-09 08:51:51

您是否尝试过使用任何 Grails 日期选择器插件?

我对日历插件有很好的体验。

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

例如,

new DomainObject(params)

您还可以像这样解析“yyyy/MM/dd”日期字符串......

new Date().parse("yyyy/MM/dd", "2010/03/18")

Have you tried using any of the Grails date picker plugins?

Ive had good experiences with the calendar plugin.

(When using the calendar plugin) When you submit the request of the date selection you can automatically bind the query parameter to the domain object you want to populate with the request.

E.g.

new DomainObject(params)

You can also parse a "yyyy/MM/dd" date string like so...

new Date().parse("yyyy/MM/dd", "2010/03/18")
世界如花海般美丽 2024-09-09 08:51:51

@Don 感谢上面的回答。

这是自定义编辑器的替代方案,它先检查日期时间,然后检查日期格式。

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) : "")
    }
}

@Don Thanks for the answer above.

Here's an alternative to the custom editor that checks first date time then date format.

Groovy, just add semi colons back in for 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) : "")
    }
}
毁我热情 2024-09-09 08:51:51

Grails 版本 >= 2.3

用于将字符串转换为日期的 localeAware 版本

在 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 的名称“defaultDateConverter”实际上是重要(覆盖默认日期转换器)

Grails Version >= 2.3

A localeAware version to convert strings to date

In 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
    }
}

In conf/spring/resources.groovy:

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

The bean's name 'defaultDateConverter' is really important (to override the default date converter)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文