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