【问题标题】:Spring change date input format春改日期输入格式
【发布时间】:2012-05-13 14:23:04
【问题描述】:

我正在尝试创建一个表单,它将返回一个带有时间戳的对象。现在,输入格式必须是yyyy-MM-dd HH:mm:ss,我希望时间戳输入格式为dd.MM.yyyy HH:mm - 如何更改输入格式?

对象类:

public class Test {
    private Timestamp dateStart;

    public Timestamp getDateStart() {
        return dateStart;
    }
    public void setDateStart(Timestamp dateStart) {
        this.dateStart = new Timestamp(dateStart.getTime());
    }
}

控制器方法:

@RequestMapping(value="test", method = RequestMethod.POST)
public View newTest(@ModelAttribute("test") Test test, Model model) {
    //save the Test object
}

jsp形式:

<form:form action="service/test" method="post" modelAttribute="test">
    <form:input type="text" path="dateStart" />
</form:form>

当格​​式不正确时,我收到此错误:

Field error in object 'test' on field 'dateStart': rejected value [22.05.2012 14:00]; codes [typeMismatch.test.dateStart,typeMismatch.dateStart,typeMismatch.java.sql.Timestamp,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [test.dateStart,dateStart]; arguments []; default message [dateStart]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.sql.Timestamp' for property 'dateStart'; nested exception is org.springframework.core.convert.ConversionFailedException: Unable to convert value "22.05.2012 14:00" from type 'java.lang.String' to type 'java.sql.Timestamp'; nested exception is java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]]

【问题讨论】:

标签: spring jakarta-ee spring-mvc


【解决方案1】:

感谢 Tomasz 我得到了答案,我必须在控制器中添加一个 binder 方法:

@InitBinder
public void binder(WebDataBinder binder) {binder.registerCustomEditor(Timestamp.class,
    new PropertyEditorSupport() {
        public void setAsText(String value) {
            try {
                Date parsedDate = new SimpleDateFormat("dd.MM.yyyy HH:mm").parse(value);
                setValue(new Timestamp(parsedDate.getTime()));
            } catch (ParseException e) {
                setValue(null);
            }
        }
    });
}

【讨论】:

    【解决方案2】:

    仅供参考,这是一个完整的 Timestamp 自定义编辑器的代码(它也支持 getAsText()),由 http://adfinmunich.blogspot.com/2011/04/how-to-write-sqltimestamppropertyeditor.html 提供,只需更改 DEFAULT_BATCH_PATTERN 以匹配您所需的日期/时间戳模式,或者在您构建时发送所需的模式SqlTimestampPropertyEditor:

    package org.springframework.beans.custompropertyeditors;
    
    import java.beans.PropertyEditorSupport;
    import java.sql.Timestamp;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    
    /**
     * Property editor for java.sql.Timestamp, supporting SimpleDateFormat.
     * 
     * Using default Constructor uses the pattern yyyy-MM-dd
     * Using the constructor with String, you can use your own pattern.
     * 
     */
    public class SqlTimestampPropertyEditor extends PropertyEditorSupport {
    
    public static final String DEFAULT_BATCH_PATTERN = "yyyy-MM-dd";
    
    private final SimpleDateFormat sdf;
    
    /**
     * uses default pattern yyyy-MM-dd for date parsing.
     */
    public SqlTimestampPropertyEditor() {
        this.sdf = new SimpleDateFormat(SqlTimestampPropertyEditor.DEFAULT_BATCH_PATTERN);
    }
    
    /**
     * Uses the given pattern for dateparsing, see {@link SimpleDateFormat} for allowed patterns.
     * 
     * @param pattern
     *            the pattern describing the date and time format
     * @see SimpleDateFormat#SimpleDateFormat(String)
     */
    public SqlTimestampPropertyEditor(String pattern) {
        this.sdf = new SimpleDateFormat(pattern);
    }
    
    /**
     * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
     */
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
    
        try {
            setValue(new Timestamp(this.sdf.parse(text).getTime()));
        } catch (ParseException ex) {
            throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);
        }
    }
    
    /**
     * Format the Timestamp as String, using the specified DateFormat.
     */
    @Override
    public String getAsText() {
        Timestamp value = (Timestamp) getValue();
        return (value != null ? this.sdf.format(value) : "");
    }
    }
    

    要使用这个类,你需要定义以下@InitBinder:

    @InitBinder
    public void binder(WebDataBinder binder) {binder.registerCustomEditor(Timestamp.class,
        new org.springframework.beans.custompropertyeditors.SqlTimestampPropertyEditor();}
    

    如果您想使用非默认日期/时间戳模式,请在构造函数中将其提供给 SqlTimestampPropertyEditor,因此对于此特定示例,您可以使用:

    @InitBinder
    public void binder(WebDataBinder binder) {binder.registerCustomEditor(Timestamp.class,
        new org.springframework.beans.custompropertyeditors.SqlTimestampPropertyEditor("dd.MM.yyyy HH:mm");}
    

    【讨论】:

    • 我不建议这样做,因为您使用相同的 SimpleDateFormat 实例进行解析,这不是线程安全的 (stackoverflow.com/questions/6840803/…)。当然,代码的结构组织得更好,但它是不安全的,除非您为每个请求创建一个新的 SimpleDateFormat。
    猜你喜欢
    • 1970-01-01
    • 2019-03-28
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多