spring mvc post convert long to date?

时间:2016-04-05 13:51:57

标签: spring spring-mvc

Spring mvc控制器

@RequestMapping(method = RequestMethod.POST)
public Result<String> create(CouponModel model) {//...}

CuponModel:
private Date beginDate;
private Date overDate;

打电话给这个api

curl -X POST -d '...&beginDate=1459500407&overDate=1459699200' 'http://localhost:8080/coupons'
Error 400 Bad Request

首先没有错误日志输出,然后更改为debug级别,输出

Field error in object 'couponModel' on field 'beginDate': rejected value [1459500407]; codes [typeMismatch.couponModel.beginDate,typeMismatch.beginDate,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [couponModel.beginDate,beginDate]; arguments []; default message [beginDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'beginDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type @javax.validation.constraints.NotNull java.util.Date for value '1459500407'; nested exception is java.lang.IllegalArgumentException]

如何让参数在模型中长时间转换为日期?

我尝试了以下方式,但它不起作用

public class StringToDateConverter implements Converter<String, Date> {

    @Override
    public Date convert(String source) {
        if (source == null ) {
            return null;
        }
        return new Date(Long.valueOf(source));
    }

}

@Configuration
@EnableWebMvc
public class WebMvcContext extends WebMvcConfigurerAdapter {
    @Override
    public void addFormatters(FormatterRegistry registry) {
         registry.addConverter(new StringToDateConverter());
    }
}

2 个答案:

答案 0 :(得分:3)

在Controller中添加一个init绑定器,告诉spring它应该如何转换日期:

示例:

@InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat,false));
    }

答案 1 :(得分:0)

谢谢@Rafik BELDI!我的方式是

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
        public void setAsText(String value) {
             setValue(new Date(Long.valueOf(value)));
        }

    });
}

参考Spring MVC - Binding a Date Field