input 태그의 date 타입을 자바 Date 객체로 파싱하기

sangeun jo·2022년 6월 19일
0

form에 다음과 같이 input 태그를 date타입으로 설정하고 제출하면 Date 타입으로 자동으로 변환되지 않는다.

<input type="date" name="date"/>

400 bad request 에러를 얻게 된다.

This application has no explicit mapping for /error, so you are seeing this as a fallback.
There was an unexpected error (type=Bad Request, status=400).
Validation failed for object='formDto'. Error count: 1
org.springframework.web.method.annotation.ModelAttributeMethodProcessor$1: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'formDto' on field 'date': rejected value [2022-06-07]; codes

date 입력 폼을 받는 Controller에 다음과 같은 코드를 넣으면 된다.

@InitBinder
private void dateBinder(WebDataBinder binder) {
	SimpleDateFormat dateFormat = new
    SimpleDateFormat("yyyy-MM-dd"); //날짜 형식은 알아서 정하기
    CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
    binder.registerCustomEditor(Date.class, editor);
}

출처

나는 DateUtil 클레스를 만들어서 필요한 컨트롤러에 extends하여 사용하고 있다.

public class CheckReqController extends DateUtil
profile
코더가 아니라 개발자가 되자

0개의 댓글