본문 바로가기
dev/Spring

[Spring] String <-> Date 타입변환

by dev_Step 2022. 1. 20.

jsp 파일에서 

String type으로 넘어오는 데이터를 VO에서 변환하는 방법은

 

VO에서 @DateTimeFormat(pattern = "yyyy/MM/dd")

로 변수에 선언해주는 방법이 있다.

 

 

/sample/ex03?title=test&dueDate=2022/01/20 

get 방식으로 호출하면 Contorller로 넘어와서,

 

/ex03을 차자 ex03메서드로 연결된다.

이때 매개변수로 TodoVO 를 가지고 오는데 넘어온 데이터는 자동으로 맵핑된다.

 

이때 VO 에서 dueDate 값이 @DateTimeFormat(pattern = "yyyy/MM/dd") 로 패턴이 정해져있다.

실행결과를 보면 dueDate가 자동으로 Date로 변환이 되어 나오는 것을 확인할 수 있다.

 

 

dueDate의 패턴을 @어노테이션의 패턴과 다르게 할경우 WARN이 발생하는것을 볼수 있다.

 

WARN : org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'todoVO' on field 'dueDate': rejected value [2022-01-20]; codes [typeMismatch.todoVO.dueDate,typeMismatch.dueDate,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [todoVO.dueDate,dueDate]; arguments []; default message [dueDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'dueDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.format.annotation.DateTimeFormat java.util.Date] for value '2022-01-20'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2022-01-20]]]

'dev > Spring' 카테고리의 다른 글

[Spring] Controller Return Type  (0) 2022.01.20
[Spring] Model  (0) 2022.01.20
[Spring] SQL 어노테이션 사용, XML 사용  (0) 2022.01.16
[Spring] DI 예제1  (0) 2022.01.11
[Spring] 스프링의 주요특징  (0) 2022.01.11