Spring MVC - 绑定日期字段

时间:2010-09-14 00:02:30

标签: java spring spring-mvc

对于表示字符串,数字和布尔值的请求参数,Spring MVC容器可以将它们绑定到开箱即用的类型属性。

如何让Spring MVC容器绑定表示Date的请求参数?

说到这一点,Spring MVC如何确定给定请求参数的类型?

谢谢!

2 个答案:

答案 0 :(得分:63)

  

Spring MVC如何确定给定请求参数的类型?

Spring使用ServletRequestDataBinder绑定其值。该过程可以描述如下

/**
  * Bundled Mock request
  */
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("name", "Tom");
request.addParameter("age", "25");

/**
  * Spring create a new command object before processing the request
  *
  * By calling <COMMAND_CLASS>.class.newInstance(); 
  */
Person person = new Person();

...

/**
  * And Then with a ServletRequestDataBinder, it bind the submitted values
  * 
  * It makes use of Java reflection To bind its values
  */
ServletRequestDataBinder binder = ServletRequestDataBinder(person);
binder.bind(request);

在幕后,DataBinder实例在内部使用BeanWrapperImpl实例,该实例负责设置命令对象的值。使用getPropertyType方法,它将检索属性类型

如果你看到上面提交的请求(当然是使用模拟),Spring会调用

BeanWrapperImpl beanWrapper = new BeanWrapperImpl(person);

Clazz requiredType = beanWrapper.getPropertyType("name");

然后

beanWrapper.convertIfNecessary("Tom", requiredType, methodParam)
  

Spring MVC容器如何绑定表示Date的请求参数?

如果您需要特殊转换的人性化数据表示,则必须注册PropertyEditor例如,java.util.Date不知道13/09/2010是什么,所以你告诉Spring < / p>

  

Spring,使用以下PropertyEditor

转换此人类友好日期
binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
    public void setAsText(String value) {
        try {
            setValue(new SimpleDateFormat("dd/MM/yyyy").parse(value));
        } catch(ParseException e) {
            setValue(null);
        }
    }

    public String getAsText() {
        return new SimpleDateFormat("dd/MM/yyyy").format((Date) getValue());
    }        

});

当调用convertIfNecessary方法时,Spring会查找任何注册的PropertyEditor,它负责转换提交的值。要注册您的PropertyEditor,您可以

Spring 3.0

@InitBinder
public void binder(WebDataBinder binder) {
    // as shown above
}

旧式Spring 2.x

@Override
public void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
    // as shown above
}

答案 1 :(得分:31)

作为Arthur非常完整的答案的补充:在简单的Date字段的情况下,您不必实现整个PropertyEditor。您只需使用CustomDateEditor即可使用日期格式:

//put this in your Controller 
//(if you have a superclass for your controllers 
//and want to use the same date format throughout the app, put it there)
@InitBinder
private void dateBinder(WebDataBinder binder) {
            //The date format to parse or output your dates
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
            //Create a new CustomDateEditor
    CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
            //Register it as custom editor for the Date type
    binder.registerCustomEditor(Date.class, editor);
}