타입변환 : String -> int
데이터 검증 : month는 1~12에 있는지
BindingResult 에러, 결과 저장
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;
양방향 타입 변환(String -> 타입, 타입 -> String)
특정 타입이나 이름의 필드에 적용 가능
모든 컨트롤러 내에서의 변환 - WebBindingInitializer를 구현후 등록
특정 컨트롤러 내에서의 변환 - 컨트롤러에 @InitBinder가 붙은 메서드를 작성
@InitBinder
public void toDate(WebDataBinder binder) {
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
binder.registerCustomEditor(Date.class, new CustomDateEditor(df, false));
}
단방향 타입 변환(타입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를 등록 가능.
양방향 타입 변환(String -> 타입, 타입 -> String)
바인딩할 필드에 적용 - @NumberFormat, @DateTimeFormat
@DateTimeFormat(pattern="yyyy/MM/dd")
Date birth;
@NumberFormat(pattern="###,###")
BigDecimal salary;