LoginSignup
0
0

More than 5 years have passed since last update.

JAX-RS(Jersey)でyyyy-MM-dd形式の日付パラメータをjava.util.Dateで受け取る

Posted at

以下のようなProviderを作成する。

package com.example.helloworld;

import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import javax.ws.rs.ext.Provider;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Jerseyでyyyy-MM-dd形式をDateとして受け取るコンバータ
 */
@Provider
public class DateParamConverterProvider implements ParamConverterProvider {

    @Override
    public <T> ParamConverter<T> getConverter(Class<T> type, Type genericType, Annotation[] annotations) {
        if (type.equals(Date.class)) {
            return (ParamConverter<T>) new DateParamConverter();
        } else {
            return null;
        }

    }

    private static class DateParamConverter implements ParamConverter<Date> {
        @Override
        public Date fromString(String value) {
            if (value == null) {
                return null;
            }
            try {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                // 2016-01-32が2016-02-01と扱われないように
                simpleDateFormat.setLenient(false);
                return simpleDateFormat.parse(value);
            } catch (ParseException e) {
                throw new RuntimeException("parse失敗: " + value, e);
            }
        }

        @Override
        public String toString(Date value) {
            return value.toString();
        }

    }
}

Dropwizardの場合は、以下のような感じでApplicationで上記Providerを登録。

public class HelloWorldApplication extends Application<HelloWorldConfiguration> {

.
.
.
    @Override
    public void run(HelloWorldConfiguration configuration, Environment environment) {

        environment.jersey().register(DateParamConverterProvider.class);
.
.
.

しかし、Dropwizardには io.dropwizard.jersey.params.DateTimeParam が用意されているので日付に限ってはそちらを使った方が良い。Optionalにラップ出来るみたいだし。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0