반응형
★ 스프링 MVC 중요!!
[스프링 공식문서 https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc]
[여기에 적은 거는 강의 내용을 다 적은게 아니라서 강의자료 보면서 이 게시글 참고하자.]
[스프링 MVC 이해 - Response] - 심화반 1주차 1-8강의
- 스프링 MVC?
- MVC (Model - View - Controller) 디자인 패턴
- Server 에서 HTML 을 내려 주는 경우
1. 정적 (static) 웹 페이지
- Controller
- Client 의 요청을 Model 로 받아 처리
- 예) 회원가입을 위한 개인 정보들 (id, password, name)
- Client 에게 View (정적 웹 페이지, HTML) 를 내려줌
- Client 의 요청을 Model 로 받아 처리
2. 동적 (dynamic) 웹 페이지
- Controller
- Client 의 요청을 Model 로 받아 처리 [여기서 Model은 클라이언트에서 서버로 보내는 어떤 정보]
- Template engine 에게 View, Model 전달
- View: 동적 HTML 파일
- Model: View 에 적용할 정보들
[여기서 Model은 Contoller가 템플릿 엔진에게 보내는 Model이다.]
- Template engine
- View 에 Model 을 적용 → 동적 웹페이지 생성
- 예) 로그인 성공 시, "로그인된 사용자의 id" 를 페이지에 추가
- Template engine 종류: 타임리프 (Thymeleaf), Groovy, FreeMarker, Jade 등 (스프링에서 JSP 이용은 추천하지 않고 있음)
- View 에 Model 을 적용 → 동적 웹페이지 생성
- Client 에게 View (동적 웹 페이지, HTML) 를 내려줌
[HTTP 메시지]
- (1) 메시지 구조
- 시작줄 (start line)
- Response 에선 '상태줄 (status line)' 이라고 부름
- 헤더 (headers)
- 본문 (body)
- (2) Request 메시지
- 시작줄: API 요청 내용
- GET naver.com HTTP/1.1
- 헤더
- "Content type"
- 없음
- HTML <form> 태그로 요청 시
- Content type: application/x-www-form-urlencoded
- AJAX 요청
- Content type: application/json
- "Content type"
- 본문
- GET 요청 시: (보통) 없음
- POST 요청 시: (보통) 사용자가 입력한 폼 데이터
- name=홍길동&age=20
- (3) Response 메시지
- 상태줄: API 요청 결과 (상태 코드, 상태 텍스트)
[상태 코드 - 서버에서 클라이언트의 요청을 어떻게 처리했는지 결과를 담고있다.] - HTTP/1.1 404 Not Found
- 헤더
- "Content type"
- 없음
- Response 본문 내용이 HTML 인 경우
- Content type: text/html
- Response 본문 내용이 JSON 인 경우
- Content type: application/json
- "Location"
- Redirect 할 페이지 URL
-
Location: <http://localhost:8080/hello.html>
- "Content type"
- 본문
- HTML
- <!DOCTYPE html>
<html>
<head><title>By @ResponseBody</title></head>
<body>Hello, Spring 정적 웹 페이지!!</body>
</html>
- <!DOCTYPE html>
- JSON
- {
"name":"홍길동",
"age": 20
}
- {
- HTML
- 상태줄: API 요청 결과 (상태 코드, 상태 텍스트)
[Controller 와 HTTP Response 메시지]
-> 스프링 MVC에서 대부분 좌절을 많이 겼는다. 그이유는 Response에 대한 형태가 다양하게 이루어져 있어서 어렵다
-> controller에서 보낼 수 있는 Response 종류를 살펴보자.(정적 웹페이지, 동적 웹페이지, JSON데이터)
표를 자주 보면서 익히자
- 강의자료 정적 웹페이지에서 2.Redirect에서 더 추가
- Response header에 있는 내용
- Location: 내가 Redirect 할 주소를 뜻한다.
- http://localhost:8080/hello/response/html/redirect 이렇게 적으면 redirect한 곳으로 간다.
- ★ 서버 개발자 입장에서 중요한 거
Redirection 시킬 때는 redirect라고하고 뒤에 Path(경로)를 써주면 된다.
@Controller
@RequestMapping("/hello/response")
public class HelloResponseController {
@GetMapping("/html/redirect")
public String htmlFile() {
return "redirect:/hello.html";
}
}
- 강의자료 정적 웹페이지에서 3. Template engine 에 View 전달 에서 더 추가
-
- http://localhost:8080/hello/response/html/templates
- return "hello" 스트링을 리턴했다. 이 스트링이 view를 전달해준다.
"hello"가 view name이름로 전달이 되었다.
-
@GetMapping("/html/templates")
public String htmlTemplates() {
return "hello";
}
타임리프 default 설정
- prefix: classpath:/templates/
- suffix: .html
resources/templates/hello.html
- 강의자료 정적 웹페이지에서 4. @ResponseBody 에서 더 추가
- http://localhost:8080/hello/response/html/templates
- @ResponseBody
- View 를 사용하지 않고, HTTP Body 에 들어갈 String 을 직접 입력
- ★ @Response를 적어주면 view를 통과하지 않는다. 그러니깐 tempengine르로 넘기는 게 아니라 html 메시지를 그냥 body에 넣어준다.
@GetMapping("/body/html")
@ResponseBody
public String helloStringHTML() {
return "<!DOCTYPE html>" +
"<html>" +
"<head><title>By @ResponseBody</title></head>" +
"<body> Hello, 정적 웹 페이지!!</body>" +
"</html>";
}
- @RestController
- = @Controller + @ResponseBody
- [코드스니펫] HelloRestController.java
- JSON형식 데이터를 받을 때 @ResponseBody를 주로 사용
@Controller와 @ResponseBody를 항상 같이 써주는게 불편하다.
=>그래서 불편한 점을 고치기 위해서 @RestController라고 해부면 마치 @ResponseBody가 모든 메서드에 포함이 된 걸로 나온다.
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
@RestController
@RequestMapping("/hello/rest")
public class HelloRestController {
@GetMapping("/json/string")
//@RestController를 써주면 여기에 @ResponseBody를 써준 것과 같다.
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;
}
}
반응형
'JAVA' 카테고리의 다른 글
[JAVA/SpringBoot] 객체 중복 생성 문제 해결 (1-14) (0) | 2022.05.27 |
---|---|
[JAVA/SpringBoot] Controller, Service, Repository 역할 (1-12)★★ (0) | 2022.05.27 |
[JAVA/SpringBoot] AllInOneController 의 문제점 (1-11) (0) | 2022.05.27 |
[JAVA/SpringBoot] 관심상품 등록 API 구현하기 (1-10) (0) | 2022.05.27 |
[JAVA/SpringBoot] 스프링 심화 강의 1주차(1-9) (0) | 2022.05.27 |