[22/01/21] 타임리프 th:value와 th:field의 충돌

Que Lin·2022년 1월 21일
0

1day 1commit

목록 보기
14/63

게시글을 저장할 때 th:object - th:field를 사용해서 id, name값을 만들고 th:value의 값을 보내려 하는데 오류가 났다.

오류가 난 코드 부분

: 로그인 한 유저의 이메일, 아이디를 세션값으로 저장해서 작성자의 value를 세션값에 담아 보내려 했다.

작성자 : <p th:text="${session['loginEmail']}"></p>
        <input type="text" th:field="*{boardWriter}"th:value="${session['loginEmail']}" hidden>
        <input type="text" th:field="*{memberId}"th:value="${session['loginId']}" hidden>

The given id must not be null!

이런 오류가 떴다. controller에 시스아웃을 찍어보니 id값, email값이 null이었다. 값이 null이라면 잘못 보냈다는 것~

해결

: th:value와 th:field의 충돌때문인 것 같으므로, th:field을 사용하지 않고 name을 생성하여 보낸다.

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <meta charset="UTF-8">
    <title>게시글작성</title>
</head>
<body>
    <form class="form-control" action="/board/save" method="post" th:object="${board}" enctype="multipart/form-data">
        작성자 : <p th:text="${session['loginEmail']}"></p>
        <input type="text" name ="boardWriter" th:value="${session['loginEmail']}" hidden>
        <input type="text" name="memberId" th:value="${session['loginId']}" hidden>
        비밀번호 : <input th:class="form-control" type="password" th:field="*{boardPassword}" placeholder="비밀번호">
        <p th:if="${#fields.hasErrors('boardPassword')}" th:errors="*{boardPassword}" th:errorclass="field-error"></p>
        제목 : <input th:class="form-control" type="text" th:field="*{boardTitle}">
        <p th:if="${#fields.hasErrors('boardTitle')}" th:errors="*{boardTitle}" th:errorclass="field-error"></p>
        내용 : <input th:class="form-control" type="text" th:field="*{boardContents}">
        <p th:if="${#fields.hasErrors('boardContents')}" th:errors="*{boardContents}" th:errorclass="field-error"></p>

        <label for="memberProfile">업로드 사진 선택</label>
        <input th:class="form-control" type="file" id="memberProfile" th:field="*{boardFile}">
        <input class="btn btn-outline-success" type="submit" value="글작성">

    </form>
</body>
</html>
profile
1일 1커밋 1일 1벨로그!

0개의 댓글