본문 바로가기
스터디/Spring

Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDateTime' for property 'localDateTime' 에러 해결

by Big Sun 2022. 10. 7.
728x90

문제 인식

 

로그에 나온 WARN 중에 중요한 문장만 선별해서 아래에 적어보겠습니다.

org.springframework.validation.BeanPropertyBindingResult: 1 errors<EOL>Field error in object 'boardForm' on field 'localDateTime': rejected value [2022-10-07T22:42]
[typeMismatch.boardForm.localDateTime,typeMismatch.localDateTime,typeMismatch.java.time.LocalDateTime,typeMismatch]
Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDateTime' for property 'localDateTime'
ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.time.LocalDateTime] for value '2022-10-07T22:42'

 

 

 

문제 상황

 

View

<form action="/boards/new" method="post">
  <fieldset>
    <ul>
      <li><label>제목<input type="text" id="title" name = "title"></label></li>
      <li><label>작성자<input type="text" id="writer" name="writer" th:value="${member.memberName}" readonly></label></li>
      <li><label>내용<textarea id="content" name="content" rows="4" cols="50"></textarea></label></li>
      <li><label>작성일<input type='datetime-local' name='localDateTime'/></label></li>
      <li><label>공개범위<input type='radio' name='range' value='ALL'  checked="checked" />모두에게 공개<input type='radio' name='range' value='ONLY_UNNORMAL' />장애학우들에게만 공개</label></li>
    </ul>
    <button type="submit">글 작성</button>
  </fieldset>
  </fieldset>
</form>

DTO

@Data
public class BoardForm {

    private String title;
    private String writer;
    private String content;
    private LocalDateTime localDateTime;
    private Range range;
}

 

Controller

@PostMapping("/new")
    public String writeBoard(BoardForm boardForm,Board board,HttpServletRequest httpServletRequest){
        HttpSession session = httpServletRequest.getSession();
        Member loginMember = (Member) session.getAttribute(SessionConstants.LOGIN_MEMBER);
        board.setMemberId(loginMember.getMemberId());
        board.setTitle(boardForm.getTitle());
        board.setWriter(boardForm.getWriter());
        board.setContent(boardForm.getContent());
        board.setLocalDateTime(boardForm.getLocalDateTime());
        board.setRange(boardForm.getRange());
        boardService.insertBoard(board);
        return "redirect:/boards/list";
    }

 

 

@ModelAttribute는 파라미터 옆에 생략되어있습니다

 

참고) @ModelAttribute는 외부 데이터가 빈에 등록된 객체로 자동으로 변환되어 사용할 수 있도록 해주는 어노테이션이고, 이는 파라미터 옆에 기본적으로 생략되어있다.

 

String 타입에서 LocalDateTime으로 바인딩이 되지 않고 있습니다.

 

문제 해결

 

@DateTimeFormat(pattern = "yyyy-MM-dd 'T' HH:mm")을 사용!

 

여기서 pattern은 각자 로그를 잘 확인하고 그에 맞춰서 pattern을 작성해야한다.

@Data
public class BoardForm {

    private String title;
    private String writer;
    private String content;
    @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm")
    private LocalDateTime localDateTime;
    private Range range;
}

 

문제해결이 될 줄 알았으나.. 또 다시 에러가 떴다.

 

DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors<EOL>Field error in object 'board' on field 'localDateTime': rejected value [2022-10-07T22:42];

 

board에서도 같은 에러가 확인되었습니다. 

 

그런데 왜 board에서도 같은 에러가 나올까요??

 

그 이유는 컨트롤러에서 BoardForm,Board 두개 클래스 모두에 대해서 파라미터를 요구하고 있으므로, 스프링이 유사해보이는 클래스 넣어주는데 마침 두 클래스 모두 localDateTime을 가지고 있어, 둘 다 넣어 주었다.

따라서, 둘 다 형변환 오류가 나지 않게, 조치를 취해줘야한다.

 

 

위의 과정을 반복하면...

 

public class Board {

    private Integer boardId;
    private Integer memberId;
    private String title;
    private String writer;
    private String content;

    @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm")
    private LocalDateTime localDateTime;

    private Range range;
    
    ...
    }

 

 

해결되었습니다!!

 

DTO와 ENTITY의 관계에 대해서 공부하여 코드를 수정해보겠습니다!!(파라미터 값을 2개나 받을 필요가 없음, DTO만 있어야함)

 

도움을 주신 분 너무 감사합니다!

728x90