본문 바로가기
Project/토이 프로젝트

[CRUD프로젝트] : thymeleaf list로 값 받아오기 (번외)

by 오주현 2022. 7. 1.
반응형

View에서 List로 값을 뿌려주고 수정한 뒤 값을 받아서 다시 Controller로 값을 가져오는 방법에 대해 적어본다.

public class UpdateUserDto {

    private List<UserDto> updateUserList;

}

List로 받을 값을 먼저 DTO를 통해 List로 받아준다.

List<UserDto> userDtoList = userService.readAllUser();
UpdateUserDto updateUserDto = new UpdateUserDto();
updateUserDto.setUpdateUserList(userDtoList);

model.addAttribute("updateUserDto", updateUserDto);

전체 유저 정보를 조회한 userDtoList를 위에서 만들어준 UpdateUserDto 인스턴스를 생성해서 담아주고 model 객체에 담아 view로 보내준다.

<form th:action="@{/crud/update}" method="post" th:object="${updateUserDto}">

        <div class="divTable minimalistBlack">
            <div class="divTableHeading">
                <div class="divTableRow">
                    <div class="divTableHead">아이디</div>
                    <div class="divTableHead">비밀번호</div>
                </div>
            </div>
            <div class="divTableBody">
                <div class="divTableRow" th:each="m: ${updateUserDto.updateUserList}">
                    <div class="divTableCell"><input type="text" th:field="${updateUserDto.updateUserList[__${mStat.index}__].userId}"></div>
                    <div class="divTableCell"><input type="text" th:field="${updateUserDto.updateUserList[__${mStat.index}__].userPw}"></div>
<!--                    <div class="divTableCell"><input type="text" name="userId" id="userId" th:value="${m.userId}"></div>-->
<!--                    <div class="divTableCell"><input type="text" name="userPw" id="userPw" th:value="${m.userPw}"></div>-->
                </div>
            </div>
        </div>

        <button th:type="submit" th:text="저장하기"></button>
    </form>

updateUserDto 전체를 오브젝트로 받기로 하고 each문은 updateUserDto에 있는 updateUserList로 값을 뿌려준다. 값을 뿌려주면서 input 타입의 text로 값을 받을 수 있게 한다. 이때 뿌려주는 값은 th:field="${updateUserDto.updateUserList[__${mStat.index}__].userPw}"이렇게 해주면 updateUserDto에 있는 updateUserList에 있는 userPw 파라미터 값을 불러올 수 있게 된다.

찾아봐도 이렇게 값을 받는 예시가 많이 없어서 남긴다.

반응형

댓글