HTTP 메시지
헤더랑 바디가 나누어져 있고 스타트라인이 나누어져있다.
templates 폴더 하위 html
@GetMapping("/html/templates")
public String htmlTemplates() {
return "hello";
}
hello 스트링을 리턴
스트링이 hello를 view name으로 전달
타임리프 default 설정
prefix: templates 폴더에서 찾아라 이 view를 찾으면 hello 스트링을 중심으로 앞에는 /templates/ 가 붙고
Suffix:.html
뒤에는 html
@GetMapping("/body/html")
@ResponseBody
public String helloStringHTML() {
return "<!DOCTYPE html>" +
"<html>" +
"<head><meta charset=\"UTF-8\"><title>By @ResponseBody</title></head>" +
"<body> Hello, 정적 웹 페이지!!</body>" +
"</html>";
}
@ResponseBody 추가-> view를 제공하는 것이 아니라 이 스트링 내용을 바디에 채워줘 라는 뜻
content type: text/html ->헤더 내용
바디에는 html 내용이 들어옴 그 내용이 response에 들어온 것 이 부분이 바디가 됨 return 된 내용이 여기에 그대로 들어옴
@ResponseBody를 추가하면 view를 통과하지 않는다. 템플릿 엔진으로 넘기는게 아니라 이 메시지를 본문(바디로) 넘겨준다.
@GetMapping("/html/dynamic")
public String helloHtmlFile(Model model) {
visitCount++;
model.addAttribute("visits", visitCount);
// resources/templates/hello-visit.html
return "hello-visit";
}
private static long visitCount = 0;
@GetMapping("/json/string")
@ResponseBody
public String helloStringJson() {
return "{\"name\":\"BTS\",\"age\":28}";
}
response content type : text/html
html 내용을 내린 것이아니라 response 바디에다 json 내용을 내렸는데 content type이 application/json이 아니라 text/html
사실은 잘못된 형태
@GetMapping("/json/class")
@ResponseBody
public Star helloJson() {
return new Star("BTS", 28);
}
response content type: application/json
servlet을 사용할때는 java객체를 json형태로 변환하는 것을 직접 바꿔줘야 했었는데 spring에서는 json 형태를 어떻게 만드는지에 대해 신경쓰지않고 그냥 객체만 넘겨주면 알아서 json형태로 바꿔줌
@Restcontroller
@ResponseBody: json을 내릴 때 주로 사용
@RestController
@RequestMapping("/hello/rest")
public class HelloRestController {
@GetMapping("/json/string")
public String helloHtmlString() {
return "<html><body>Hello @ResponseBody</body></html>";
}
@GetMapping("/json/list")
public List<String> helloJson() {
List<String> words = Arrays.asList("Hello", "Controller", "And", "JSON");
return words;
}
}
원래 string을 내려주는 경우에는 템플릿 엔진을 통해 view로 전달하는 것인데
@RestController을 붙여주면 자동으로 메소드 윗 부분에 @ResponseBody가 추가 되는 것이라고 볼 수 있다.
클라이언트요청 -> DispatcherServlet (frontcontroller): API를 처리해 줄 controller를 찾아서 그 요청을 전달(Handler mapping에는 path와 controller 함수가 매칭 되어있음, controller에서 mapping 한 정보들을 다 모아놓음, 즉 Handler mapping을 통해 어느 controller에 전달해야하는지 알 수 있음)-> controller->Dispathces
GET: 주소창에 정보가 들어감
POST: 주소창에 정보를 숨기고 바디에 들어감
그럼 어떻게 로그인을 유지하지?
클라이언트가 서버에 1번 요청-> 서버가 세션 ID를 생성, 응답 헤어에 전달-> 클라이언트가 쿠키 저장-> 클라이언트가 서버에 쿠키값 포함하여 2번 요청-> 서버가 세션 ID확인하고, 1번 요청과 같은 클라이언트임을 인지
모듈 별로 잘 분리 우리가 원하는 기능만 잘 가져가다 레고처럼 조립해서 사용가능
서버에 필요한 인증 및 인가를 위해 많은 기능을 제공
2주차 때는 강의를 들으면서 스프링의 전체적인 흐름이 뚝 뚝 끊기는 느낌이었다면, 이번 주에는 코드의 생략된 부분을 구체적으로 알게 되면서 흩어져 있던 개념들이 하나씩 연결되는 느낌을 받았다. 혼자서 코드를 짜보면서 다시 한번 개념과 흐름을 되짚어봐야 할 것 같다.
민지님 4주차 WIL 올려주세요 현기증나요