쭈녁 2022. 11. 15. 19:21

타임리프 프로젝트 적용

<form action="post.html" th:action th:object="${post}" method="post">
        <div>
            <div>카테고리</div>
            <select th:field="*{categoryType}" class="form-select">
                <option value="">== 카테고리 선택 ==</option>
                <option th:each="categoryType: ${categoryTypes}" th:value="${categoryType.code}"
                        th:text="${categoryType.displayName}">FREE</option>
            </select>
        </div>
        <hr class="my-4">
        <div>
            <label for="title">제목</label>
            <input type="text" id="title" th:field="*{title}" class="form-control" placeholder="제목을 입력하세요">
        </div>
        <div>
            <label for="contents">내용</label>
            <input type="text" id="contents" th:field="*{contents}" class="form-control" placeholder="내용을 입력하세요">
        </div>

th:object="${post}" : <form>에서 사용할 객체(post)를 지정한다. 

그 후 th:field="*{itemName}" 로 post객체의 인스턴스를 가져올 수 있다. HTML작성 시  ${item.itemName}로 작성되던 코드와 동일하다.

 

    @GetMapping("/posts/add")
    public String addForm(Model model) {
        model.addAttribute("post", new Post());
        return "/post/addForm";
    }

    @PostMapping("/posts/add")
    public String addPost(@ModelAttribute Post post, RedirectAttributes redirectAttributes) {
        Post savedPost = postService.save(post);
        redirectAttributes.addAttribute("postId", savedPost.getId());
        redirectAttributes.addAttribute("status", true);
        return "redirect:/post/{postId}";
    }

1. PostController에서 빈 Post 객체를 모델로 넣어 주고 이를 GetMapping을 통해 페이지를 렌더링 한다.

2. Post객체가 성공적으로 저장되면 staus를 true로 바꿔주고 PostId를 파라미터로 받아 해당 페이지로 리다이랙트 해준다.

 

타임리프 셀렉트 박스

- HTML

        <div>
            <div>카테고리</div>
            <select th:field="*{categoryType}" class="form-select">
                <option value="">== 카테고리 선택 ==</option>
                <option th:each="categoryType: ${categoryTypes}" th:value="${categoryType.code}"
                        th:text="${categoryType.displayName}">FREE</option>
            </select>
        </div>

th:field="{categoryType}"을 통해 Post 객체의 categoryType 인스턴스를 참조한다

이하 th:each="categoryType: ${categoryTypes}"를 통해 Controller에 ModelAtrribute로 주입된 categoryTypes를 참조해준다. 

categoryTypes의 값은 CategoryType 객체의 값을 참조한다

 

- Controller

   @ModelAttribute("categoryTypes")
    public List<CategoryType> categoryTypes() {
        List<CategoryType> categoryTypes = new ArrayList<>();
        categoryTypes.add(new CategoryType("자유게시판", "자유 게시판"));
        categoryTypes.add(new CategoryType("공연게시판", "공연 게시판"));
        categoryTypes.add(new CategoryType("중고거래", "중고거래"));
        return categoryTypes;
    }

 

-CategoryType 객체

@Data
@AllArgsConstructor
public class CategoryType {
    private String code;
    private String displayName;

}