<정적 컨텐츠>
html을 그대로 웹 브라우저로 내려준다.
우선적으로 컨트롤러 찾고, 없다면 resource:static에서 찾는다.
< MVC(Model, View, Controller) 템플릿 엔진>
템플릿 엔진이 서버에서 html 동적인 처리를 한 후, 웹 브라우저로 내려준다.
@Controller
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;
@Controller
public class HelloController {
@GetMapping("hello")
public String hello(Model model){
model.addAttribute("data","Hello!!");
return "hello";
}
@GetMapping("hello-mvc")
public String helloMVc(@RequestParam (name="name") String name, Model model){
model.addAttribute("name",name);
return "hello-template";
}
}
@RequestParam
HTTP 요청 파라미터를 받을 수 있다. 파라미터 이름으로 바인딩 하는 방법!!
RequestParam("가져올 데이터 이름")[데이터 타입] [데이터 담을 변수] 형태로 사용함
String, int 같은 단순 타입에서 @ReqeustParam 생략 가능
Model 객체를 이용해 view로 값을 넘겨받음
name= 이름 지정
required=기본값 true 일때 해당 파라미터 없으면 HTTP 상태 코드 400 반환
false인 경우 예외 발생 X
@ResponseBody
HTTP의 body에 문자 내용 직접 반환
'viewResolver' 대신 'HttpMessageConverter' 동작
요쳥한 클라이언트에 그대로 내려감
템플릿 엔진과 다르게 view가 없..음
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","Hello!!");
return "hello";
}
@GetMapping("hello-mvc")
public String helloMVc(@RequestParam (name="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;
}
}


<API>
html 파일 자체가 아닌 데이터 포맷(json)으로 클라이언트에 전달
@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으로 반환을 해준다 (HTTP 기반의 API 제공)
데이터 표현 방식
XML vs JSON
JSON는 key:value 의 쌍으로 이루어진 구조로, 클라이언트 - 서버 간 통신을 할때 많이 사용된다
'spring & java' 카테고리의 다른 글
| 스프링 MVC / 기본 애노테이션 정리 (0) | 2024.07.08 |
|---|---|
| 싱글톤 패턴 기초 (1) | 2024.02.19 |
| [java] Map 사용방법 (0) | 2024.01.25 |
| Optional <t> 이란? (1) | 2024.01.06 |
| [java] BufferedReader 로 문자열 입력받기 (0) | 2023.07.30 |