2-30 데이터 변환과 검증(1)

서현우·2022년 5월 28일
0

복습

목록 보기
22/34

WebDataBinder

타입변환 : String -> int
데이터 검증 : month는 1~12에 있는지
BindingResult 에러, 결과 저장

RegisterController에 변환기능 추가

Data타입 변환 1

@InitBinder
public void toDate(WebDataBinder binder) {
	SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
	//스프링이 제공하는 CustomDateEditor를 이용해서 변환. String -> Date
	binder.registerCustomEditor(Date.class, new CustomDateEditor(df, false));

Data타입 변환 2

public class User {
	private String id;
	private String pwd;
	private String name;
	private String email;
	@DateTimeFormat(pattern="yyyy/MM/dd") //위의 1과 동일
	private Date birth;
	private String[] sns;
	private String[] hobby;

PropertyEditor

양방향 타입 변환(String -> 타입, 타입 -> String)
특정 타입이나 이름의 필드에 적용 가능

  • 디폴트 PropertyEditor - 스프링이 기본적으로 제공
  • 커스텀 PropertyEditor - 사용자가 직접 구현. PropertyEditorSupport를 상속하면 편리.

모든 컨트롤러 내에서의 변환 - WebBindingInitializer를 구현후 등록
특정 컨트롤러 내에서의 변환 - 컨트롤러에 @InitBinder가 붙은 메서드를 작성

@InitBinder
public void toDate(WebDataBinder binder) {
	SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
	binder.registerCustomEditor(Date.class, new CustomDateEditor(df, false));
}

Converter

단방향 타입 변환(타입A -> 타입B)
PropertyEditor의 단점을 개선(stateful -> stateless)

public class StringToStringArrayConverter implements Converter<String, String[]> {
	@Override
	public String[] convert(String source) {
		return source.split("#"); //String -> String[]
	}
}

ConversionService - 타입 변환 서비스를 제공. 여러 Converter를 등록 가능.

Formatter

양방향 타입 변환(String -> 타입, 타입 -> String)
바인딩할 필드에 적용 - @NumberFormat, @DateTimeFormat

@DateTimeFormat(pattern="yyyy/MM/dd")
Date birth;

@NumberFormat(pattern="###,###")
BigDecimal salary;

타입변환 우선순위

  1. 커스텀 PropertyEditor
  2. ConversionService
  3. 디폴트 PropertyEditor
profile
안녕하세요!!

0개의 댓글