@InitBinder

Yuno·2024년 8월 19일
0

Spring MVC 에서 사용되는 어노테이션으로, 특정 컨트롤러 내에서 바인딩 설정을 사용자 정의할 때 사용됨. 주로 폼 데이터를 객체로 바인딩할 때, 그 데이터를 변환하거나 유효성 검사를 수행할 수 있도록 커스터마이즈된 설정을 할 수 있음


👉 주요 사용 예시

  1. 커스텀 에디터 등록 : 특정 필드나 객체 타입에 대해 커스텀 변환 로직을 정의할 수 있음
  2. Validator 등록 : 특정 객체에 대해 커스텀 유효성 검사를 적용할 수 있음

👉 사용 방법

@InitBinder 어노테이션을 사용한 메서드는 컨트롤러에서 요청을 처리하기 전에 호출되며, 주로 WebDataBinder 객체를 매개변수로 받아 처리함
커스텀 에디터 등록

@Controller
public class UserController {
	
    @InitBinder
    public void initBinder(WebDataBinder binder) {
    	// String을 Date 로 변환하는 커스텀 에디터 등록
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }
    
    @PostMapping("/register")
    public String registerUser(@ModelAttribute UserForm userForm) {
    	// userForm 객체는 데이터 바인딩 후 유효성 검사가 수행됨
        return "registrationSuccess";
    }
}

SimpleDateFormat 을 사용하여 "yyyy-MM-dd" 형식의 문자열을 Date 객체로 변환하는 커스텀 에디터를 등록함. 이렇게 하면 폼에서 날짜 데이터를 받아올 때, Spring이 이를 자동으로 Date 객체로 변환해 줌


특정 필드에 대한 커스텀 에디터 등록

@Controller
public class UserController {
	
    @InitBinder
    public void initBinder(WebDataBinder binder) {
    	// 특정 필드에 대한 커스텀 에디터 등록
        binder.registerCustomEditor(String.class, "username", new PropertyEditorSupport() {
        	@Override
			public void setAsText(String text) {
        		setValue(text.trim());
	        }
    	});
	}
	
    @PostMapping("/register")
    public String registerUser(@ModelAttribute UserForm userForm) {
    	// userForm 객체의 "username" 필드에서 공백이 제거된 상태로 바인딩
        return "registrationSuccess";
    }
}

"username" 필드에 대해 커스텀 에디터를 등록하여, 사용자로부터 입력받은 값을 트리밍(앞 뒤 공백 제거) 한 후 바인딩함


커스텀 Validator 등록

@Controller
public class UserController {
	
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
    	binder.addValidators(new UserFormValidator()); // 커스텀 Validator 추가
    }
    
    @PostMapping("/register")
    public String registerUser(@ModelAttribute @Validated UserForm userForm, BindingResult result) {
    	if (result.hasErrors()) {
        	return "registrationForm";
        }
        // 유효성 검사를 통과한 경우 등록 처리
        return "registrationSuccess";
    }
}

UserFormValidator 라는 커스텀 Validator를 등록하여, UserForm 객체에 대한 유효성 검사를 수행함. 검사 결과는 BindingResult 에 저장되며, 오류가 있는 경우 다시 폼을 보여주게 됨

profile
Hello World

0개의 댓글