2016-04-05 16 views
0

Spring MVCのコントローラコールがこのAPIは、spring mvc post変換Long to Date?

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

最初は何もエラーログ出力、そしてdebugレベルに変化

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

CuponModel: 
private Date beginDate; 
private Date overDate; 

、パラメータlongに変換してみましょうする方法

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

答えて

3

はそれが日付を変換する必要がありますどのように春を伝えるために、あなたのコントローラ内のinitバインダーを追加動作しません:

例:

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

ええ、感謝を参照してくださいです!できます。このパラメータがこのようなものなら 'beginDate = 06-04-2016&overDate = 10-04-2016'ですが、私は' new Date(1459500407) ' – zhuguowei

+0

としたいのですが、私の方法がうまくいかない理由は分かりますか? – zhuguowei

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