WEB/Spring MVC 2

스프링 MVC 2편 - 스프링 통합과 폼

Tony Lim 2021. 8. 14. 14:23
728x90

html 에서 id , name ,value(객체 안에있는 값을 출력) attribute 를 자동으로 생성하는 방법 

    @GetMapping("/add")
    public String addForm(Model model) {
        model.addAttribute("item",new Item());
        return "form/addForm";
    }
    <form action="item.html" th:action th:object="${item}" method="post">
        <div>
            <label for="itemName">상품명</label>
            <input type="text" id="itemName" th:field="*{itemName}" class="form-control" placeholder="이름을 입력하세요">

빈 객체를 넘겨주고 html 에서 th:object 로 받아온다. 

th:field 에서 받아온 객체는 * 로 표시가되고 그 안의 프로퍼티를 접근한다. th:field="${item.itemName}" 이렇게 써도 무방하다. 

이렇게 하면 name 이 잘못되었을때도 오류페이지를 띄워준다.

 

 

체크박스

html에서 체크 박스를 선택하지 않고 폼을 전송하면 open 등등 필드 자체가 서버로 전송이 되지 않는다. null값이 서버로 가게된다.

logging.level.org.apache.coyote.http11=debug 를 application.yml 에 추가해주면 세세한 http request/response를 볼 수 있다.

스프링 MVC에서 _open 처럼 기존 체크 박스 이름앞에 underscore를 붙여서 전송하면 체크를 해제 했다고 인식할 수 있다. 따라서 체크를 해제한 경우 여기에서 open 은 전송되지않고 _open 만 전송이 되는데 이경우 MVC는 체크를 해제 했다고 판단한다.

하지만 thymeleaf 에서 th:field="*{open}" 을 해주면 히든(underscore) 까지 알아서 생성 해 준다... 

또한 html은 checked attribute가 존재하기만해도 체크박스가 체크되는데 이러한 것들도 th:field가 알아서 해준다. 체크가 되있으면 알아서 check attribute를 추가하고 안되어있으면 알아서 뺀다.

 

Spring 에서 메소드안에 argument로 @ModelAttribute써주는것말고 메소드 위에다가 써주면 해당 controller class 안에서 동작하는 모든 메소드들은 인제 model 안에 @ModelAttribute 가 return 해주는 것들을 model 에 담게 된다. 

    @ModelAttribute("regions")
    public Map<String,String> regions(){
        Map<String,String> regions = new LinkedHashMap<>();
        regions.put("SEOUL","서울");
        regions.put("BUSAN","부산");
        regions.put("JEJU","제주");
        return regions;
    }

 

 

multi checkbox

<div>등록 지역</div>
    <div th:each="region : ${regions}" class="form-check form-check-inline">
        <input type="checkbox" th:field="*{regions}" th:value="${region.key}" class="form-check-input">
        <label th:for="${#ids.prev('regions')}" th:text="${region.value}" class="form-check-label">서울</label>
    </div>

#ids.prev('regions')  위의 필드에 th:field="*{regions}" 에서 아이디 값을 자동으로 가지고 온다.

 

 

 

 

728x90