JAVA

[JAVA/SpringBoot] 스프링 심화 강의 1주차(1-8)

wonderson 2022. 5. 27. 10:54
반응형

★ 스프링 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
    1. Client 의 요청을 Model 로 받아 처리
      • 예) 회원가입을 위한 개인 정보들 (id, password, name)
    2. Client 에게 View (정적 웹 페이지, HTML) 를 내려줌

 

 2. 동적 (dynamic) 웹 페이지

  • Controller
    1. Client 의 요청을 Model 로 받아 처리  [여기서 Model은 클라이언트에서 서버로 보내는 어떤 정보]
    2. Template engine 에게 View, Model 전달
      1. View: 동적 HTML 파일
      2. Model: View 에 적용할 정보들
        [여기서 Model은 Contoller가 템플릿 엔진에게 보내는 Model이다.]
    3. Template engine
      1. ViewModel 을 적용 → 동적 웹페이지 생성
        1. 예) 로그인 성공 시, "로그인된 사용자의 id" 를 페이지에 추가
        2. Template engine 종류: 타임리프 (Thymeleaf), Groovy, FreeMarker, Jade 등 (스프링에서 JSP 이용은 추천하지 않고 있음)
    4. Client 에게 View (동적 웹 페이지, HTML) 를 내려줌

[HTTP 메시지]

  • (1) 메시지 구조

  1. 시작줄 (start line)
    1. Response 에선 '상태줄 (status line)' 이라고 부름
  2. 헤더 (headers)
  3. 본문 (body)
  • (2) Request 메시지
    1. 시작줄: API 요청 내용
    2. GET naver.com HTTP/1.1
    3. 헤더
      • "Content type"
        1. 없음
        2. HTML <form> 태그로 요청 시
          1. Content type: application/x-www-form-urlencoded
        3. AJAX 요청
          1. Content type: application/json
    4. 본문
      1. GET 요청 시: (보통) 없음
      2. POST 요청 시: (보통) 사용자가 입력한 폼 데이터
        1. name=홍길동&age=20
  • (3) Response 메시지
    1. 상태줄: API 요청 결과 (상태 코드, 상태 텍스트)
      [상태 코드 - 서버에서 클라이언트의 요청을 어떻게 처리했는지 결과를 담고있다.]
    2. HTTP/1.1 404 Not Found
    3. 헤더
      • "Content type"
        1. 없음
        2. Response 본문 내용이 HTML 인 경우
          1. Content type: text/html
        3. Response 본문 내용이 JSON 인 경우
          1. Content type: application/json
      • "Location" 
      • Redirect 할 페이지 URL
      • Location: <http://localhost:8080/hello.html>
        
    4. 본문
      1. HTML
        1. <!DOCTYPE html>
          <html>
          <head><title>By @ResponseBody</title></head>
          <body>Hello, Spring 정적 웹 페이지!!</body>
          </html>
      2. JSON
        1. {
          "name":"홍길동",
          "age": 20
          }

[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 전달 에서 더 추가
      1. http://localhost:8080/hello/response/html/templates
      2. 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;
    }
}
반응형