이 험난한 세상에서어어~

thymeleaf, Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long' 본문

Spring/error

thymeleaf, Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'

토끼띠NJW 2023. 7. 10. 11:50

오류 발생

소설 정보 수정 기능을 추가하다가 아래와 같은 오류를 만났다.

Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'

 

오류를 찬찬히 읽어보니 내가 string으로 선언한 부분이 long으로 변환이 안 된다는 말 같은데... 어느 부분에서 이런 문제가 생긴지 찾느라 시간이 좀 걸렸다.

 

그리하여 겨우겨우 찾은 오류의 이유는 바로 URI 때문이었다.

오류 발견

보면 알겠지만, URI에 전혀 엉뚱한 값이 들어가 있다.

 

내가 의도한 결과가 전혀 아닌데...

오류 원인

일단 소설 정보를 수정하는 하는 URI를

"/novels/{novelId}/update"

로 만들었다. 저기 novelId은 소설의 id로 long 형으로 변환해서 사용한다. 

여기까지는 문제가 없다. 하지만, form을 채우고 이를 post로 보내는 방식에서 문제가 생긴 것이다.

처음에는 html의 action을 아래 부분처럼 작성했다.

<form role ="form" action="@{/novels/{novelId}/update}" th:object="${novelForm}"  method="post">

나는 저 {novelId} 부분에 당연히 변수 값이 들어갈 것이라고 생각했지만, 타임리프는 이걸 string으로 보내서 string이 long  형으로 변환할 수 없다는 에러가 나온 것이다.

나: {novelId}로 써 주면 타임리프가 자동으로 안에 id 값을 넣어서 컨트롤러에 전달하겠지?
타임리프: (novelId에 값을 안 넣고 문자열로 보내버림)
컨트롤러: novelId를 long형으로 변환해야 하는데 왜 숫자 대신 novelId가 들어있지? 오류!

이렇게 된 것이다...

 

이 부분을 해결하기 위해서 @{novelForm.id}를 넣어주거나 아니면 +로 문자열 더하기를 시도했는데, 제대로 되지 않았다.

오류 해결 방법

해결 방법은 간단한데 그냥 action 부분을 지워주면 된다.

타임리프가 form을 보낼 위치를 자동으로 잡아주는 건지 action을 지웠더니 해결이 됐다!!

참고

thymeleaf 공식 문서를 보니 주소 안에 변수를 넣는 방법이 나와있었다.

<a th:href="@{/order/{id}/details(id=3,action='show_all')}">

정확하게 명시하고 싶으면 이 방법을 써도 좋을 듯하다.

https://www.thymeleaf.org/doc/articles/standardurlsyntax.html

 

Standard URL Syntax - Thymeleaf

The Thymeleaf standard dialects –called Standard and SpringStandard– offer a way to easily create URLs in your web applications so that they include any required URL preparation artifacts. This is done by means of the so-called link expressions, a type

www.thymeleaf.org

 

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

Package name does not correspond to the file path 오류  (0) 2023.06.29
[Spring Boot]Could not resolve property  (0) 2023.05.21