Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

말하는 햄zzi

HTTP 본문

Java/Spring

HTTP

대양파 2023. 7. 23. 03:49
728x90

HTTP란?

 

: 데이터 손실 X 가정하에 개발

 하이퍼 텍스트 전송하기 위한 프로토콜

 HyperText Transfer Protocol

 

HTTP Request

 

Request Line 

 

- GET : 데이터 조회

- POST : 데이터 포함 요청 보냄/ 생성

- PUT : 데이터 포함 요청 보냄/ 수정 

- DELETE : 데이터 삭제 요청 

- HTTP 요청 전반적 정보 포함

 

Request Headers

 

- 요청 부수적 정보

- 어떠한 응답 기대

- 데이터 어떤형태로 해석하는지 

 

Reauest Body

 

- 전달하고자하는 실제 데이터 포함 

 

 

HTTP Response

 

Status Line

: HTTP 버전/ 상태코드/ 상태코드 메세지

 

ex)

더보기

HTTP Status Code

- 100 ~ 199 : 정보 제공 목적

- 200 ~ 299 : 요청이 성공적으로 처리되었을 경우

- 300 ~ 399 : Redirect, 클라이언트의 추가적인 행동이 필요할 경우 (301, 302)

- 400 ~ 499 : 클라이언트가 처리 불가능한 요청을 한 경우 (400 401 403 404)

- 500 ~ 599 : Internal Server Error, 서버에 문제가 생겨 처리가 불가능한 경우 (500)

 

Response Headers

 

- 응답 부수적 정보

- 해석 방식 

 

Response Body

 

- 전달하려는 실제 데이터

 

 

POSTMAN

 

Postman?

 

: API 개발 도구

Request(요청) 쉽고 자세하게 설정 가능 , Response(응답) 확인 가능 

API 문서화/ 팀원 공유 가능

 

Postman 사용방법 

 

: Slf4j<Simple Logging Facade for Java>

 

 

@Slf4j

: 자바 환경 로깅 라이브러리

 

@Slf4j 
public class MappingController

> Lombok 어노테이션 사용하여 간단하게 사용 가능 / 클래스 내 Logger 객체를 log 이름으로 주입 

 

log.info("단순 정보");
log.error("에러 발생 ");

> 로그 심각도에 따라 trace/ debug / info / warn / error 등 메서드 사용 가능 

 

 

@RequestMapping

:  같은 경로 다른 Method로 요청 받을 수 있다 

 

@Slf4j
@Controller
public class MappingController {

    @RequestMapping(
            value = "/path",
            method = RequestMethod.GET
    )
    public String getPath() {
        log.info("GET /path");
        return "index";
    }

    @RequestMapping(
            value = "/path",
            method = RequestMethod.POST
    )
    public String postPath() {
        log.info("POST /path");
        return "index";
    }

}

 

위 예시와 같은 상황시 아래 예시와 같이 Method 묶어줄 수 있다

@Slf4j
@Controller
public class MappingController {

    @RequestMapping(
            value = "/path",
            method = {RequestMethod.PUT, RequestMethod.DELETE}
    )
    public String putOrDeletePath() {
        log.info("PUT or DELETE /path");
        return "index";
    }

}

 

header 값 통해 요청 구별하는 방법

@RequestMapping(
            value = "/path",
            method = RequestMethod.POST,
            headers = "x-likelion" //요청시 header에 추가
)
public String consumePath() {
   log.info("POST /path with header x-likelion");
   return "index";
}

 

parm값 통해 요청 구별하는 방법

//요청 : http://127.0.0.1:8080/path?likelion=hihihi
    @RequestMapping(
            value = "/path",
            method = RequestMethod.POST,
            params = "likelion"
    )
    public String postPathWithParam() {
        log.info("postPathWithParam /path");
        return "index";
    }

 

PostMapping 사용

@PostMapping(
            value = "/path",
            params = "likelion=hello"
    )
    public String params() {
        log.info("POST /path with parameter likelion");
        return "index";
    }

 

@ReequestHeader

: header 값 받아 사용 가능 

 

@PostMapping("/header-one")
public String postHeader(
        @RequestHeader("x-likelion") String header //x-likelion 이름으로 들어온..
) {
    log.info("POST /header-one header : " + header);
    return "index";
}

 

@ResponseBody

: 스프링에서 비동기 처리하는경우 @Requestbody/ @Responsebody 사용

클라이언트에서 서버로 통신하는 메세지 = Request(요청) 메세지 

서버에서 클라이언트로 통신하는 메세지 = Response(응답) 메세지

클라이언트에서 서보로 요청 메세지 보낼시 , 본문에 데이터 담아 보내야하며

서버에서 클라이언트로 응답 보낼시 , 본문에 데이터 담아 보내야한다

(데이터 담은 본문 = Body)

 

 

Dto 패키지 내 , ArticleDto/ResponseDto 클래스 생성

package com.example.dto;

import lombok.Data;

// 블로그 게시글
// 게시글 - 제목
// 게시글 - 내용
/*
{
    //필드    //value
    "title": "제목",
    "content": "content"
}
*    */
@Data
public class ArticleDto {
    private String title;
    private String content;
}

 

ResponseDto.java

package com.example.dto;

import lombok.Data;

// 일반적 응답
// 상태
// 메시지
/*
{
    "status": 200,
    "message": "success"
}
* */
@Data
public class ResponseDto {
    private Integer status;
    private String message;
}

 

 

BodyController.java

 

package com.example.http;

import com.example.dto.ArticleDto;
import com.example.dto.ResponseDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@Controller
public class BodyController {
    // '/body'로 요청이 들어왔을 시,
    // ResponsDto 데이터를 표현한 JSON 응답을 반환하는 메소드
    @PostMapping("/body")
           // HTTP 응답의 Body임을 나타내는 어노테이션
    public @ResponseBody ResponseDto body() {
        ResponseDto response = new ResponseDto();
        response.setStatus(200);
        response.setMessage("success");
        return response; // 클라이언트가 이해할 수 있게 변환 후 응답
    }
}

 

> 자바 객체를 HTTP요청 body 내용으로 매핑 후 클라이언트 전송

 

>@ResponseBody가 붙은 파라미터= HTTP요청 본문 body 부분 그대로 전달 

 

더보기

@RequestBody / @ResponseBody 

클라이언트에서 서버로 필요 데이터 요청하기 위해 JSON 데이터 요청 본문에 담아 서버로 보내면,

서버는 @RequestBody 어노테이션 사용하여 HTTP 요청 본문에 담긴 값 자바객체로 변환시켜 , 객체 저장

서버 클라이언트로 응답 데이터 전송하기 위해 

@ResponseBody 어노테이션 사용 , 자바 객체 HTTP 응답 본문 객체로 변환 후 클라이언트 전송 

 

728x90
반응형

'Java > Spring' 카테고리의 다른 글

Skeleton 프로젝트  (0) 2023.07.13
Optional<T> / JPA  (0) 2023.07.13
IOC(Inversion of Control)-(2)  (0) 2023.07.13
IOC(Inversion of Control)-(1)  (0) 2023.07.12
MyBatis  (0) 2023.07.11