【问题标题】:Grails request parameter type conversionGrails请求参数类型转换
【发布时间】:2009-09-02 21:32:12
【问题描述】:

在我的 Grails 应用程序中,我需要将请求参数绑定到命令对象的 Date 字段。为了执行字符串到日期的转换,需要在grails-app\conf\spring\resources.groovy中注册一个合适的PropertyEditor

我添加了以下 bean 定义:

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

    beans = {
        paramDateEditor(CustomDateEditor, new SimpleDateFormat("dd/MM/yy"), true) {} 
    }

但我仍然收到错误消息:

java.lang.IllegalArgumentException: Could not parse date: Unparseable date: "04/01/99"]

我认为我定义 bean 的方式可能有问题,但我不知道是什么?

【问题讨论】:

  • 在您的 SimpleDateFormat 中,“月份”的“mm”应为“MM”。我做了一个快速测试,SimpleDateFormat 的 parse() 不会用你的格式和输入字符串抛出 IllegalArgumentException,所以这可能不是问题的原因,但值得注意。 :)
  • 谢谢,我更改了代码(及以上)中的格式字符串,但问题仍然存在
  • 使用CustomDateEditor.class 作为paramDateEditor() 的第一个参数怎么样?我只是在这里往墙上扔东西,看看它是否粘住。我熟悉 Grails,但没有太多绑定 Command 对象的经验。
  • 那行不通。第一个参数必须是正在创建的 bean 的类

标签: grails spring-mvc


【解决方案1】:

您缺少的部分是注册新的属性编辑器。当我升级到 Grails 1.1 并且必须以 MM/dd/yyyy 格式绑定日期时,以下内容对我有用。

grails-app/config/spring/resources.groovy:

beans = { 
    customPropertyEditorRegistrar(util.CustomPropertyEditorRegistrar) 
}

src/groovy/util/CustomPropertyEditorRegistrar.groovy:

package util 

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

public class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar { 
  public void registerCustomEditors(PropertyEditorRegistry registry) { 
      registry.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("dd/MM/yy"), true)); 
  } 
} 

【讨论】:

    猜你喜欢
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多