[JAVA] Register request parameter type conversion with SpringBoot + MVC

Request parameter automatic type conversion by Spring MVC

Spring MVC converts request parameters to the appropriate type. The default type conversion is provided, so if you want to store it in another type (stored in your own class, a type different from the type that resolves automatically), register it in the type conversion in the Spring MVC settings. To do.

Example: Converting date input to java.time.LocalDate (java.util.Date by default)

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

The Birthday of SampleModel is of type LocalDate. This time, all parameters will be converted in the Spring MVC settings in general.

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 is a class that inherits from ʻ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);
	}

}

Recommended Posts

Register request parameter type conversion with SpringBoot + MVC
Request parameter log output sample Java & Spring MVC
Java-automatic type conversion
MySQL JSON type Value search with SpringBoot + Spring JPA