Grails 请求参数类型转换 [英] Grails request parameter type conversion

查看:22
本文介绍了Grails 请求参数类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Grails 应用程序中,我需要将请求参数绑定到命令对象的 Date 字段.为了执行字符串到日期的转换,需要注册一个适当的 PropertyEditorgrails-appconfspring esources.groovy

In my Grails app, I need to bind a request parameter to a Date field of a command object. In order to perform the String-to-Date conversion, one needs to register an appropriate PropertyEditor in grails-appconfspring esources.groovy

我添加了以下 bean 定义:

I've added the following bean definiton:

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

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

但我仍然收到一个错误:

But I'm still getting an error:

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

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

I think there's probably just something wrong with the way I've defined the bean, but I've no idea what?

推荐答案

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

The piece you are missing is registering of the new property editor. The following worked for me when I upgraded to Grails 1.1 and had to bind dates in the MM/dd/yyyy format.

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)); 
  } 
} 

这篇关于Grails 请求参数类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆