처누

[Spring] @PathVariable & Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long' 본문

java

[Spring] @PathVariable & Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'

처누 2024. 1. 20. 18:49

@GetMapping

@GetMapping("/board/detail/{id}")

 

 게시판 프로젝트 - 게시글 조회하는 기능을 구현하는 중에  {id}값을 인수로 사용하고 싶어서 구글링 해봤다.

public String showBoardContent(@PathVariable Long id, Model model) {
Board board = boardService.findByOne(id).get();
model.addAttribute("board", board);
return "/board/showBoardDetail";
}


 @PathVariable 어노테이션을 통해 {id}값을 인수로 사용할 수 있다. 여기서 중괄호{} 안에 있는 값과 인수명이 같다면 @PathVariable 옵션을 생략할 수 있지만 만약 다르게 설정한다면 옵션을 넣어줘야한다. 예를 들어

 

@GetMapping("/board/detail/{id}")
public String showBoardContent(@PathVariable("id") Long boardId, Model model) {
Board board = boardService.findByOne(boardId).get();
model.addAttribute("board", board);
return "/board/showBoardDetail";
}


 @GetMapping 어노테이션 안에 동적으로 받은 값이 'id'이고 인수로는 'boardId'로 사용하고 싶다면 @PathVariable 어노테이션 옵션안에 @GetMapping으로 받은 값을 입력해주면 된다.

java.lang.IllegalArgumentException: Name for argument of type 
     [java.lang.Long] not specified, and parameter name information 
     not available via reflection. Ensure that the compiler uses the '-parameters' flag.

 

 @PathVariable 어노테이션에서 옵션값을 생략하고 구현하다가 위와 같은 에러가 발생하는 경우가 있다.
 SpringBoot 3.2버전 이상부터는 자바 컴파일러에 -parameter 옵션을 넣어줘야 어노테이션의 옵션을 생략할 수 있다. 

 [File] - [Settings] - [Build, Execution, Deployment] - [Compiler] - [Java Compiler]에서 'Additional command line parameters'에 '-parameters'를 넣어주자.

 

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

 @GetMapping 안에 {id}값을 Long id 인수로 받아 구현하던 중 계속해서 다음과 같은 오류가 발생했다.

Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'; For input string: "${boards.id}"]

<td><a th:text="${boards.title}" th:href="@{/board/detail/${boards.id}}"></a></td>

 

 showBoardList.html에서 "${boards.id}"의 값이 String으로 들어왔고 이를 Long으로 변환을 못한다는 에러가 발생했다. 분명 나는 @PathVariable을 통해서 인수에 id값을 Long으로 받았는데 이와 같은 오류가 발생한 것이다. 이는 다음과 같이 수정하면 오류가 해결된다.

<td><a th:text="${boards.title}" th:href="@{/board/detail/{id}(id=${boards.id})}"></a></td>

 

 String으로 받은 "${boards.id}"값을 id의 자료형의 변환한 후 넘겨주면 된다.