2017-01-22 19 views
2

イベントフォームオブジェクトを受け取るSpringブートコントローラを作成しました。シリアル化されたHTML時刻フィールドをjava.time.LocalTimeに変換する

@RestController 
    @RequestMapping("/Event") 
    public class EventController { 

     @RequestMapping(value = "/create", method = RequestMethod.POST) 
     private synchronized List<Event> createEvent(Event inEvent) {  
      log.error("create called with event: " + inEvent); 
      create(inEvent); 
      return listAll(); 
     } 
    } 

イベントクラスは、この(省略ゲッター/セッター)

public final class Event { 
    private Integer id; 
    private Integer periodId; 
    private String name; 
    @DateTimeFormat(pattern = "dd/MM/yyyy") 
    private LocalDate eventDate; 
    private LocalTime startTime; 
    private LocalTime endTime; 
    private Integer maxParticipants; 
    private String status; 
    private String eventType; 
} 

私はstartTimeの上で春型の不一致エラーを取得していますし、endTimeのフィールド

Field error in object 'event' on field 'endTime': rejected value 
[12:00] codes 
[typeMismatch.event.endTime,typeMismatch.endTime,typeMismatch.java.time.LocalTime,typeMismatch] 
arguments 
[org.springframework.context.support.DefaultMessageSourceResolvable: 
codes [event.endTime,endTime] arguments [] default message [endTime]] 
default message [Failed to convert property value of type 
'java.lang.String' to required type 'java.time.LocalTime' for property 
'endTime' nested exception is 
org.springframework.core.convert.ConversionFailedException: Failed to 
convert from type [java.lang.String] to type [java.time.LocalTime] for 
value '12:00' nested exception is java.lang.IllegalArgumentException: 
Parse attempt failed for value [12:00]] 

直列化された形のように見えますデータはjQuery AJAXメソッドを使用してポストされます。シリアル化されたデータは次のようになります。

eventDate=27%2F01%2F2017&eventType=REN&maxParticipants=10&startTime=09%3A00&endTime=12%3A00 

シリアル化された時刻フィールドを正しく解析するにはどうすればよいですか?私はあなたがフォームの送信時に変換したいLocalTimeインスタンス上DateTimeFormat注釈を供給する必要がありますJavaの8

答えて

3

使用しています

。これらの注釈は、着信データが共通のISO時刻フォーマット:DateTimeFormat.ISO.TIMEに準拠することを示す必要があります。

@DateTimeFormat(iso = DateTimeFormat.ISO.TIME) 
private LocalTime startTime; 

@DateTimeFormat(iso = DateTimeFormat.ISO.TIME) 
private LocalTime endTime; 

これらの注釈を適用する前に、私が見たエラーを再現できました。これらの注釈を適用した後、コードサンプルにフォーム送信を正常にPOSTして、LocalTimeインスタンスが正しく作成されたことを確認できました。

+0

多くの時間を節約できました。アップボーニング。関連する読み物(書籍またはチュートリアル)を追加してください。ありがとうございます。 –

+1

@Vito、アップしてくれてありがとう!この質問に答えるために私が使用した唯一のリソースは、答え内から既にリンクされているJavaDocページでした。より一般的な読書資料に関しては、私はいつも公開されている[Springのドキュメント](https://spring.io/docs)がかなり良いと思ってきました。 –

関連する問題