Java Spring MVC - 绑定日期字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3705282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 03:42:58  来源:igfitidea点击:

Spring MVC - Binding a Date Field

javaspringspring-mvc

提问by Tom Tucker

For request parameters representing string, number, and boolean values, the Spring MVC container can bind them to typed properties out of the box.

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

How do you have the Spring MVC container bind a request parameter representing a Date?

你如何让 Spring MVC 容器绑定一个表示日期的请求参数?

Speaking of which, how does the Spring MVC determine the type of a given request parameter?

说到这里,Spring MVC 是如何判断给定请求参数的类型的呢?

Thanks!

谢谢!

采纳答案by Arthur Ronald

How does the Spring MVC determine the type of a given request parameter ?

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

Spring makes use of ServletRequestDataBinderto bind its values. The process can be described as follows

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 binds the submitted values
  * 
  * It makes use of Java reflection To bind its values
  */
ServletRequestDataBinder binder = new ServletRequestDataBinder(person);
binder.bind(request);

Behind the scenes, DataBinderinstances internally makes use of a BeanWrapperImplinstance which is responsible for set up the values of the command object. With getPropertyTypemethod, it retrieves the property type

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

If you see the submitted request above (of course, by using a mock), Spring will call

如果您看到上面提交的请求(当然,通过使用模拟),Spring 将调用

BeanWrapperImpl beanWrapper = new BeanWrapperImpl(person);

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

And Then

进而

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

How does Spring MVC container bind a request parameter representing a Date ?

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

If you have human-friendly representation of data which needs special conversion, you must register a PropertyEditorFor instance, java.util.Date does not know what 13/09/2010 is, so you tell Spring

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

Spring, convert this human-friendly date by using the following PropertyEditor

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

});

When calling convertIfNecessary method, Spring looks for any registered PropertyEditor which takes care of converting the submitted value. To register your PropertyEditor, you can either

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

Spring 3.0

春天 3.0

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

Old-style Spring 2.x

旧式 Spring 2.x

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

回答by Mircea Stanciu

In complement to Arthur's very complete answer : in the case of a simple Date field, you don't have to implement the whole PropertyEditor. You can just use a CustomDateEditorto which you simply pass the date format to use :

作为 Arthur 非常完整的答案的补充:在简单日期字段的情况下,您不必实现整个 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);
}