개발

@InitBinder를 통한 파라미터 변환

Domaya 2023. 1. 10. 18:40

파라미터의 수집을 binding이라고 한다.

변환이 가능한 데이터는 자동으로 변환되지만 경우에 따라서는 파라미터를 변환해서 처리해야 하는 경우도 있다.

예를 들어, 화면에서 '2018-01-01'과 같이 문자열로 전달된 데이터를 java.util.Date타입으로 변환하는 작업이 있다.

스프링 컨트롤러에서는 파라미터를 바인딩할 때 자동으로 호출되는 @InitBinder를 이용해서 이러한 변환을 처리할 수 있다.

 

package kr.or.kosa.dto;

import java.util.Date;

import lombok.Data;

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

다음과 같은 DTO가 있다.

 

package kr.or.kosa.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import kr.or.kosa.dto.TodoDto;


@Controller
@RequestMapping("/sample/*")
public class SampleController {

		@InitBinder
		public void initBinder(WebDataBinder binder) {
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(dateFormat, false));
		}
		@GetMapping("/dateformat")
		public String ex03(TodoDto todo) {
			System.out.println("todo : " + todo);
			return "";
		}
		

}

컨트롤러를 다음과 같이 작성하고

브라우저에서 http://localhost:8090/kosa/sample/dateformat?title=test&dueDate=2022-01-10 라고 호출하면

서버에서는 정상적으로 파라미터를 수집해서 처리한다.

따라서 콘솔에

위처럼 나온다~

 

혹은 날짜 변경의 경우, 파라미터로 사용되는 인스턴스에 @DateTimeFormat을 적용해서 할 수도 있다. 이 때는 @InitBinder는 필요없다.

 

package kr.or.kosa.dto;

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

DTO를 위와 같이 수정한다.

브라우저에서 http://localhost:8090/kosa/sample/dateformat?title=test&dueDate=2022/01/10라고 호출하면

 

잘 나온다.