Grails请求参数类型转换

3
在我的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异常,所以这可能不是问题的原因,但这值得注意。 :) - Rob Hruska
谢谢,我已经在代码(以及上面)中更改了格式字符串,但问题仍然存在。 - Dónal
使用 CustomDateEditor.class 作为 paramDateEditor() 的第一个参数怎么样?我只是在试探,看看这是否可行。我熟悉Grails,但对于绑定Command对象没有太多经验。 - Rob Hruska
那样行不通。第一个参数必须是正在创建的bean的类。 - Dónal
1个回答

8

你所缺少的部分是注册新属性编辑器。当我升级到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)); 
  } 
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接