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 {
@GetMapping("hello")
public String hello(Model model) {
model.addAttribute("data", "spring!!");
return "hello";
}
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam(name = "name", required = true) String name, Model model) {
model.addAttribute("name", name);
return "hello-template";
}
**// ResponseBody: http 프로토콜의 body 부분에 return 값을 직접 넣어주겠다.
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name) {
return "hello " + name; //"hello (name 변수 값)"
}**
}
html 태그를 이용해서 한 것과 같은 결과
코드를 까보면 다름
<aside> 💡 만약에 데이터를 내놓으라 한다면?
</aside>
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 {
@GetMapping("hello")
public String hello(Model model) {
model.addAttribute("data", "spring!!");
return "hello";
}
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam(name = "name", required = true) String name, Model model) {
model.addAttribute("name", name);
return "hello-template";
}
// ResponseBody: http 프로토콜의 body 부분에 return 값을 직접 넣어주겠다.
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name) {
return "hello " + name; //"hello (name 변수 값)"
}
**@GetMapping("hello-api")
@ResponseBody
public Hello helloApi(@RequestParam("name") String name){
Hello hello = new Hello();
hello.setName(name);
return hello;
}
static class Hello {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}**
}
데이터가 바로 들어가있음 - JSON 형태
Jackson: 객체를 JSON형태로 바꾸는 라이브러리들 중 하나
⭐ API는 데이터 형태로 return하는 것, template은 html 형태로 return 하는 것.