본문 바로가기

Thymeleaf

[Thymeleaf] Form 태그 작성

    @GetMapping("/admin/category/new")
    public String categoryForm(Model model){
        model.addAttribute("categoryForm", new CategoryDto());
        return "admin/adminCategoryForm";
    }

페이지에 접근 할 때, Controller에서 객체를 하나 만들어 model객체에 담아줍니다.

CategoryDto에는 name과 orderNum이 있습니다.

 

<form th:action="@{/admin/category/new}" th:object="${categoryForm}" method="post">
    <div class="form-group">
        <label for="name">카테고리 이름</label>
        <input type="text" class="form-control" id="name" th:field="*{name}">
    </div>
    <div class="form-group">
        <label for="order">순서</label>
        <input type="text" class="form-control" id="order" th:field="*{orderNum}">
    </div>
    <button type="submit" class="btn btn-primary">저장</button>
</form>

알아볼 것

1. th:action = "@{ }"

HTML에서 action과 같은 역할을 하며 URL이전에 '@'를 붙입니다.

2. th:object= "${ }"

여기서 categoryForm은 Controller에서 model에 담아서 보내진 CategoryDto객체입니다. '$'를 붙여주어야 합니다.

3. th:field=" *{ }"

th:field를 지정하면 HTML 태그에서는 id와 name 두 개가 설정이 됩니다. '*'를 붙어주어야 합니다.

field의 이름은 반드시 CategoryDto의 변수의 이름과 일치해야 합니다.

 

    @PostMapping("/admin/category/new")
    public String saveCategory(CategoryDto categoryDto){

        Category category = Category.builder()
                .name(categoryDto.getName())
                .orderNum(categoryDto.getOrderNum())
                .build();

        categoryService.saveCategory(category);

        return "redirect:/admin/category";
    }

파라미터에 CategoryDto를 받습니다. 그 이유는 위에서 GetMapping을 실행할 때 model객체에 CategoryDto를 보냈고, View에서 CategoryDto의 변수에 맞추어 form태그를 작성하여 보냈기 때문에 다시 Controller에서 받을 때도 똑같은 변수가 들어있는 객체로 받아야 하기 때문입니다.