본문 바로가기
개발/spring

spring api 데이터 받기

by 향유 2022. 11. 24.
package hello.hellospring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {

    // /hello 로 get 주소 입력시 아래 소스 매핑하라는 명령어
    @GetMapping("hello")
    public String hello(Model model){
        model.addAttribute("data","hello!!"); //모델에 정보담아서 세팅
        return "hello"; //hello.html로 model 데이터 전달 명령어
    }

    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam("name") String name, Model model){
        model.addAttribute("name",name);
        return "hello-template";
    }

    //값을 바로 페이지에 출력
    @GetMapping("hello-string")
    @ResponseBody
    public String helloString(@RequestParam("name") String name){
        return "hello" +name; //name 받은 값으로 전달
    }

    @GetMapping("hello-api")
    @ResponseBody
    public Hello helloApi (@RequestParam("name") String name){
        Hello hello = new Hello();
        hello.setName(name);
        return hello; //객체를 json으로 넘김
    }

    static class Hello{
            private String name;
            public String getName(){
                return name;
            }
            public void setName(String name){
                this.name = name;
            }
        }


}

get으로 받아온 값으로 객체 만들어 출력 및 전달

@ResponseBody => view단으로 데이터 전송이 아닌 http Body에 데이터를 전달하여 출력

httpMessageConverter 라는 내부기능 자동 동작 

-string컨버터 : 문자 처리

-json컨버터  : 객체 처리

 

 

 

 

 

댓글