개발바닥 아방수

[스프링부트] Controller, RestController, View, DTO 예제 본문

웹 개발/Java

[스프링부트] Controller, RestController, View, DTO 예제

앙큼아기 2022. 12. 21. 15:50

Controller, RestController, View 예제

  • HelloController.java
  • dispatcher -> view resolver 
  • view를 리턴해준다.
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.PathVariable;

@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("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";
    }
}

 

 

  • helloRestController
  • 화면 이동과는 상관없이 데이터를 리턴해준다.
  • helloController와 동일한 "hello" mapping이 있지만, helloRestController는 RequestMapping으로 "api"가 지정되어 있어 타고오는 경로가 다르다.
package com.jieun.chunjae.controller;

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

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class HelloRestController {
    // @RequestMapping
    @GetMapping("/hello")
    // @PostMapping         // Get으로 하든 Post로 하든 하나로 하세요~ 둘 다 사용해도 상관은 없습니다!
    public String hello(){
        return "hello";
    }

    @PostMapping("/axiostest")
    public List<Integer> axiostest(@RequestBody HashMap<String, String> param){
        List<Integer> intList = Arrays.asList(1,2,3);
        return intList;
    }

    @PostMapping("/axiostest2")
    public List<String> axiostest2(@RequestBody HashMap<String, String> param){
        List<String> intList = Arrays.asList("Tom","Jas","Tiger");
        return intList;
    }
}

 

  • hellod.html
  • helloController를 통해 보여지는 view 화면
<!DOCTYPE html>
<html lang="en">
<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">
    <title>Document</title>
</head>
<body>
    <h1 th:text="${id}">m</h1>
</body>
</html>

 

 


Controller, RestController, View, DTO 예제

-- 폼으로 내용 보내기

 

  • hello.hrml
  • 폼에 id를 주고, 스크립트단에서 이벤트를 만들어준다.
  • 해당 이벤트에서 helloRestController로 보낼 function도 생성하여 넣어준다.
<!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>



    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>

 

 

 

  • helloRestController
package com.jieun.chunjae.controller;

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

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.jieun.chunjae.dto.SampleDTO;

@RestController
@RequestMapping("/api")
public class HelloRestController {
    // @RequestMapping
    @GetMapping("/hello")
    // @PostMapping         // Get으로 하든 Post로 하든 하나로 하세요~ 둘 다 사용해도 상관은 없습니다!
    public String hello(){
        return "hello";
    }

    @PostMapping("/axiostest")
    public List<Integer> axiostest(@RequestBody HashMap<String, String> param){
        List<Integer> intList = Arrays.asList(1,2,3);
        return intList;
    }

    @PostMapping("/axiostest2")
    public List<String> axiostest2(@RequestBody HashMap<String, String> param){
        List<String> intList = Arrays.asList("Tom","Jas","Tiger");
        return intList;
    }

    @PostMapping("/dtotest")
    public void dtotest(@RequestBody SampleDTO sampleDTO){
        System.out.println(sampleDTO.toString());
        // sampleDTO.getFirst();
    }
}

 

 

  • DTO 파일 생성을 위해 다음과 같이 폴더와 파일을 생성한다.

 

  • SampleDTO.java
  • Java Code Generators(Extension으로 설치)을 사용해서 getter setter를 만든다(코드에서 우클릭)
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() + "'" +
            "}";
    }
    

}

 

 

 

  • 폼에 데이터가 잘 들어갔는지 확인하려면 다음과 같이 개발자도구 > 소스에서 디버깅 해보면 값을 확인할 수 있다.

 

 

  • helloRestController에서 디버깅하여 들어온 값을 확인할 수도 있다.

 

 

  • 코드를 돌려보면 터미널에서 다음과 같이 출력되는 것을 확인할 수 있다.