무소의 뿔처럼

@InitBinder 본문

알아두기/Spring

@InitBinder

값을변경 2023. 3. 4. 14:19

@InitBinder : 파라미터를 변환해서 처리해야 할 경우.

 

binding = 파라미터 수집

스프링 Controller에서는 파라미터를 바인딩할 때 자동으로 호출되는 @InitBinder

get으로 파라미터 받아올때 문자열=>Date로 (Controller에서)

 

DTO

package com.sun.domain;
import java.util.Date;
import lombok.Data;

@Data
public class TodoDTO {
	private String title;
	private Date dueDate;
}

 

Controller

@InitBinder
public void initBinder(WebDataBinder binder) {
 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
 binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(dateFormat, false));
}

 

get으로 'date=2023-03-04'로 요청 받으면

컨트롤러에서  'date=Sat Mar 04 00:00:00 KST 2023'으로 바꿔서 보여줌


같은 결과  (여기서 DateTimeFormat으로 처리하게 되면 @InitBinder는 필요하지 않음.)

DTO

package com.sun.domain;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import lombok.Data;

@Data
public class TodoDTO {

	private String title;
	
	@DateTimeFormat(pattern = "yyyy-MM-dd")
	private Date dueDate;
	
}

 

출처 : 코트로 배우는 스프링 웹 프로젝트 

 

 

Comments