0
2

More than 3 years have passed since last update.

SpringBoot+MVCで、リクエストパラメータの型変換を登録する

Posted at

SpringMVCによるリクエストパラメータ自動型変換

SpringMVCではリクエストパラメータを適切な型に変換します。デフォルトの型変換が提供されているので、これ以外の型(自作したクラスに格納する、自動的に解決する型とは別の型)に格納したい場合は、SpringMVCの設定にて型変換に登録します。

例:日付の入力をjava.time.LocalDateに変換する(デフォルトでjava.util.Date)場合

SampleModelController.java
import java.time.LocalDate;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import lombok.Data;

@Controller
@RequestMapping("/sample")
public class SampleModelController {
    @GetMapping
    public ModelAndView sample(ModelAndView mnv, @ModelAttribute SampleModel model) {
        mnv.addObject("model", model);
        return mnv;
    }

    @Data
    public static class SampleModel {
        private String name;
        private LocalDate birthday;
    }
}

SampleModelのbirthdayが、LocalDate型です。今回はすべてのパラメータに対し、全般的にSpringMVCの設定にて変換対象にします。

WebConfig.java
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new StringToLocalDate());
    }
}

StringToLocalDateは、org.springframework.core.convert.converter.Converter を継承したクラスです。

StringToLocalDate.java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

import org.springframework.core.convert.converter.Converter;

public class StringToLocalDate implements Converter<String, LocalDate> {

    @Override
    public LocalDate convert(String source) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/M/d");
        return LocalDate.parse(source, formatter);
    }

}
0
2
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
2