gimmickbutreal

[Spring Boot] 타임리프(Thymeleaf) URL 본문

Programming/Spring Boot

[Spring Boot] 타임리프(Thymeleaf) URL

isshosng 2022. 9. 1. 14:50

타임리프에서 링크의 주소는 th:href 속성을 사용합니다. 타임리프에서 th:href처럼 URL 주소를 나타날 때에는 반드시 @{ }에서 중괄호 안에 입력해야 합니다.

<table>
    <thead>
        <tr>
            <th>제목</th>
            <th>작성일시</th>
        </tr>
    </thead>
    <tbody>
        <tr th:each="question, index : ${questionList}">
            <td>
                <a th:href="@{|/question/detail/${question.id}|}" th:text="${question.subject}"></a>
            </td>
            <td th:text="${question.createDate}"></td>
        </tr>
    </tbody>
</table>

 

그리고 URL 주소는 문자열 /question/detail/과 자바 객체인 ${question.id} 값이 조합돼 /question/detail/${question.id}로 만들어집니다. 이처럼 문자열과 자바 객체의 값을 더할 때는 반드시 |  | 로 좌우를 감싸 주어야 합니다.

위처럼 좌우에 | 문자 없이 사용하면 오류가 발생하니 주의해야 합니다. 

 

 

요청 URL http://localhost:8080/question/detail/2의 숫자 2처럼 2번째에 올라온 글을 나타내려고 할 때 변화하는 id 값을 얻을 때에는 위와 같이 @PathVariable 애너테이션을 사용해야 합니다. 또한, 컨트롤러 내 작성한 @RequestMapping(value = "/question/detail/${question.id}") 자바코드에서 사용한 id와 @PathVariable("id")의 매개변수 이름이 동일해야 합니다.