Javaの日付データの扱いはややこしい
Java初心者には日付データを扱うのが非常にわかりにくいですよね。自分は今でもDateの扱いは調べないとできません。。。まあ覚えないといけないくらい複雑って時点で言語的にダメな気がしてるんですけど。
util.Date、sqlDate、Timestamp、Calender、LocalDate、ZoneDate、OffsetDateなどなどJava初心者には理解不能。。。
リクエストからこれらの値をどう受け取るかも最初は謎すぎた。
リクエストパラメータから文字列の日付情報を受け取る
yyyy-MM-ddとかyyyy-mm-dd hh:MMl:ssといったパターンの文字列をDate型に変換するのに@InitBinderと@ControllerAdviseを使います。
まず文字列をDate型に変換する方法としてInitBinderというものを使用します。これはControllerに渡ってくるパラメータに対して事前に処理を加えることができます。
このInitBinderをどのタイミングで実行するか定義するのにControllerAdviseを使用します。これはControllerの処理の前後に任意の処理を仕込むことができるものでこの仕組みを使ってInitBinderの処理を割り込ませます。
実装はたったこれだけです。
package com.sample.controller_advise import org.springframework.beans.propertyeditors.CustomDateEditor import org.springframework.stereotype.Component import org.springframework.web.bind.WebDataBinder import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.InitBinder import java.text.SimpleDateFormat import java.util.Date @ControllerAdvice @Component class BinderAdvise { @InitBinder fun initBinder(binder: WebDataBinder) { // 日付文字列をDateにバインドする設定 val dateFormat: SimpleDateFormat = SimpleDateFormat("yyyy-MM-dd") dateFormat.setLenient(false) binder.registerCustomEditor(Date::class.java, "startDate", CustomDateEditor(dateFormat, true)) binder.registerCustomEditor(Date::class.java, "endDate", CustomDateEditor(dateFormat, true)) // 日時文字列をDateにバインドする設定 val datetimeFormat: SimpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") datetimeFormat.setLenient(false) binder.registerCustomEditor(Date::class.java, "targetDatetime", CustomDateEditor(datetimeFormat, true)) } }
クラスの先頭に@ControllerAdviceをつけると全コントローラーに対して処理を割り込ませることができます。DIしないといけないので@Componetもつけてください。
@InitBinderがリクエストパラメータから受け取ったデータに対して任意の処理を実行できるものです。
startDate,endDate,targetDatetimeという文字列はリクエストパラメータとして送られてくる変数名を設定しています。
文字列の日付データを数行で定義できて、全部のControllerに対して適用できるのでここら辺の仕組みは非常に簡単です。
設定も複数かけて2種類のフォーマットを定義しても問題ありません。
おすすめ書籍
Springの概要からインストール方法、各コア機能(Security, Sessionなど)の解説が体系的にまとめられています。2018年に出版されたばかりなので情報も新しいです。これからSpring Bootでアプリケーション開発をしたい方の最初に読む一冊としておすすめします。対象は初心者だけでなく上級者まで幅広く学べるので是非読んでみてください!
髙妻智一
最新記事 by 髙妻智一 (全て見る)
- Polkadot(Substrate)のアドレスとトランザクションについて - 2023-03-09
- 【無料公開】「Goで始めるBitcoin」3章 Bitcoinノードとの通信 技術書典8 - 2020-03-08
- エンジニアがゼロから技術ブログを書くための方法をまとめました - 2019-05-25
コメントを残す