Spring boot

Response 와 MIME TYPE 에 이해

섹시꽃남민우 2023. 4. 10. 17:06
학습 목표 

1. MIME TYPE text/plain 에 이해 
2. MIME TYPE application/json 에 이해 
3. dto 설계 및 요청과 응답 방식에 이해 
4. ReseponseEntity 개념과 custom 방법에 이해
package com.example.demo3.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo3.dto.User;

@RestController
@RequestMapping("/api")
public class ApiController {
	
	// 80 포트 번호는 주소창에서 생략 가능 합니다.
	// http://localhost:80/api/hello
	// http://localhost/api/hello
	@GetMapping("/hello")
	public String hello() {
		return "hello"; 
	}
	
	// MEME TYPE 타입 : text/plain 으로 응답 처리 해주세요 
	// http://localhost/api/text 
	// 응답 결과 -> 응답 : text/plain
	@GetMapping("/text")
	public String text() {
		return "응답 : text/plain";
	}
	
	// response json 형식으로 내려주기
	// -> /api/json
	@PostMapping("/json")
	public User json(@RequestBody User user) {
		System.out.println(user.toString());
		// 응답 Object type 
		return user;
	}
	
}
Spring Boot는 기본적으로 ContentNegotiation이라는 기능을 제공하여 
Accept 헤더에 따라 응답의 Content-Type 을 자동으로 결정합니다.
이 기능은 스프링 프레임워크의 ContentNegotiatingViewResolver를 확장하여 구현됩니다.
GET /index.html HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:85.0) Gecko/20100101 Firefox/85.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1
HTTP/1.1 200 OK
Date: Wed, 31 Mar 2023 01:23:45 GMT
Server: Apache/2.4.41 (Unix)
Last-Modified: Mon, 01 Feb 2021 12:34:56 GMT
ETag: "1234567890"
Content-Length: 1234
Content-Type: text/html

<!DOCTYPE html>
<html>
<head>
    <title>Example Page</title>
</head>
<body>
    <h1>Welcome to Example Page</h1>
    <p>This is an example page.</p>
</body>
</html>