Grails请求参数类型转换
问题内容:
在我的Grails应用程序中,我需要将请求参数绑定到Date
命令对象的字段。为了执行字符串到日期的转换,需要在其中注册适当的PropertyEditor。grails-app\conf\spring\resources.groovy
我添加了以下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的方式可能有问题,但是我不知道是什么?
问题答案:
您缺少的是正在注册新的属性编辑器。当我升级到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));
}
}