개발바닥 아방수

[스프링부트] 타임리프 방식으로 form 보내기 본문

웹 개발/Java

[스프링부트] 타임리프 방식으로 form 보내기

앙큼아기 2022. 12. 21. 16:24

타임리프 방식으로 form을 보내는 것은

form 자체에서 DTO 객체를 던져주는 것이 키포인트다.

그렇기 때문에, controller에서 view를 던져줄 때부터 DTO 객체를 생성하여

model.addAttribute로 던져주는 것이 중요하다.

 

  • hello.html
  • 하단 코드에서 타임리프 이용하여 보내기 주석 부분을 보면 된다.
  • html에서부터 sampleDTO로 controller에 보내는 방식이다.
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- axios 라이브러리 추가 : 라이브러리를 static 쪽에 파일자체를 넣던가, 이렇게 cdn으로 가져올 수 있음 -->
    <!-- cdn으로 불러오면 버전관리를 따로 하지 않아도 괜찮다는 장점이 있음 -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <title>Document</title>
</head>
<body>
    <!-- 자바스크립트 이용하여 보내기 -->
    <h1>form axios</h1>
    <form action="#" id="bform">
        <p>first : <input type="text" id="restFirst"/></p>
        <p>second : <input type="text" id="restSecond"/></p>
        <p>last : <input type="text" id="restLast"/></p>
        <p><input type="submit" value="submit"/></p>
    </form>

    <!-- 타임리프 이용하여 보내기 -->
    <h1>form sumbit</h1>
    <form action="#" th:action="@{/testDTO}" th:object="${sampleDTO}" method="post">
        <p>first : <input type="text" th:field="*{first}"/></p>
        <p>last : <input type="text" th:field="*{last}"/></p>
        <p><input type="submit" value="submit"/></p>
    </form>



    hello view

    <div><a href="/link">link test</a></div>
    <div><a th:href="@{'/link/' + &{url}}">link test</a></div>


    Hello~~~~
    <h1 ht:if="${message} != null" th:text="${message}"></h1>

    <h1>List</h1>
    <div>
        <ul>
            <li th:each="list: ${list}" th:text="${list}"></li>
        </ul>
    </div>

    <!-- 아이디(ulist)에 접근해서 엘리먼트를 추가해주는 방식 -->
    <div id="ulist"> </div>
    <button onclick="testAxios()">click me</button>
    <script th:inline="javascript">
        //console.log('test');
        function testAxios(){
            axios.post('/api/axiostest2',{parameter:'ppp'})
                .then(function(res){
                    const data = res.data;
                    data && data[0] && data.forEach(i => {
                        const newLi = document.createElement('li');
                        newLi.style.color = 'blue';
                        newLi.innerHTML = i;
                        document.getElementById('ulist').appendChild(newLi);
                    });
                })
        }
        //testAxios();    // 함수 실행

        // 폼에 이벤트 추가
        document.getElementById('bform').addEventListener('submit', e=> {
            e.preventDefault();
            const first = document.getElementById('restFirst').value;
            const second = document.getElementById('restSecond').value;
            const last = document.getElementById('restLast').value;
            dtoTest({first, second, last});
        });

        function dtoTest(param) {
            axios.post('/api/dtotest', param)
                .then(res=>{

                });
        }
    </script>
</body>
</html>

 

 

 

  • helloController.java
  • mapping 값인 hello에 들어갈 때부터 폼에서 가지고 있을 sampleDTO 객체가 필요하다.
  • 그러기 때문에 타임리프 폼에서 보낼 객체 생성하여 세팅한다.
  • model.addAttribute("sampleDTO", new SampleDTO());
package com.jieun.chunjae.controller;

import java.util.Arrays;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import com.jieun.chunjae.dto.SampleDTO;

@Controller
public class HelloController {
    @GetMapping("/hello")       // 이 경로를 찾아서 View를 띄워줌 -> 이 이름과 파일의 이름이 동일해야 찾아서 view를 보여줄 수 있다.
    public String helloView(Model model){
        
        // 리스트 생성
        List<String> list = Arrays.asList("a","b","c");
        model.addAttribute("list", list);
        model.addAttribute("url", 33);
        // 타임리프 폼에서 보낼 객체 생성하여 세팅
        model.addAttribute("sampleDTO", new SampleDTO());
        
        // 텍스트 그대로 보내줘서 뿌려주기
        model.addAttribute("message", "ㅎㅎㅎㅎㅎㅎㅎㅎ");
        return "hello";

        // 실질적으로 데이터를 보내는 것은 이게 끝임.
        // 비동기로 불러온 데이터를 추가해 줄 예정임.
        // DAO에 객체 주고받는 것 연습하고

        
    }

    @GetMapping("/link")
    public String linkTest() {
        return "link";
    }

    @GetMapping("/link/{id}")
    public String linkView(@PathVariable("id") int id, Model model) {
        model.addAttribute( "id", id);
        return "hellod";
    }

    // @ModelAttribute 이거 쓰고 객체이름을 쓰면 알아서 이름 맞춰서 던져줌(first면 알아서 first getter setter 찾는다)
    @PostMapping("/testDTO")
    public String formTest(@ModelAttribute("sampleDTO") SampleDTO sampleDTO) {
        System.out.println(sampleDTO.toString());
        return "redirect:/";
    }
}

 

 

  • (지난 게시글에서 만든) SampleDTO.java
package com.jieun.chunjae.dto;

public class SampleDTO {
    private Long id;
    private String first;
    private String second;
    private String last;


    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirst() {
        return this.first;
    }

    public void setFirst(String first) {
        this.first = first;
    }


    public String getSecond() {
        return this.second;
    }

    public void setSecond(String second) {
        this.second = second;
    }


    public String getLast() {
        return this.last;
    }

    public void setLast(String last) {
        this.last = last;
    }


    @Override
    public String toString() {
        return "{" +
            " first='" + getFirst() + "'" +
            ", second='" + getSecond() + "'" +
            ", last='" + getLast() + "'" +
            "}";
    }
    

}

 

 

결과

 

  • 다음과 같이 SampleDTO에서 설정한 toString()에 맞게 출력된다.