반응형
여기서 Spring boot 간단하게 시작
@RequestMapping 구현
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
@RequestMapping("/api/v1/get-api")
public class GetController {
}
- RequestMapping 애너테이션을 별다른 설정 없이 선언하면 HTTP의 모든 요청을 받는다.
- 그러나 GET 형식의 요청만 받기 위해서 애너테이션에 별도 설정이 필요
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/get-api")
public class GetController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String getHello(){
return "Hello World";
}
}
- 스프링 4.3 버전 이후로 새로 나온 아래의 애너테이션을 사용하기 때문에 @Requestmapping 애너테이션은 더 이상 사용되지 않음
- 이 책에서도 특별히 @RequestMapping을 활용해야하는 내용이 아니라면 아래의 각 HTTP 메서드에 맞는 애너테이션 사용 예정
- @GetMapping
- @PostMapping
- @PutMapping
- @DeleteMapping
결과
매개변수가 없는 Get 메서드 구현
@GetMapping(value = "/name")
public String getName(){
return "Flature";
}
@PathVariable
- 값을 간단히 전달할 때 주로 사용하는 방법
@GetMapping(value = "/variable1/{variable}")
public String getVariable1(@PathVariable String variable){
return "variable";
}
@GetMapping(value = "/variable2/{variable}")
public String getVariable2(@PathVariable("variable") String var){
return "var";
}
@RequestParam
- URL 경로에 값을 담아 요청을 보내는 방법 외에도 쿼리형식으로 값 전달 방법
- URl에서 ‘?’를 기준으로 우측에 ‘{키}={값}’ 형태로 구성된 요청을 전송하는 방법
// <http://localhost:8080/api/v1/get-api/request1?name=flature&email=thinkground.flature@gmail.com&organization=thinkground>
@GetMapping(value = "/request1")
public String getRequestParam1(
@RequestParam String name,
@RequestParam String email,
@RequestParam String organization
){
return name + " " + email + " " + organization;
}
URL 길이제한
- URL에는 길이 제한이 있다 단, HTTP 스펙이 아니라 브라우저, 서버, 프록시마다 구현상 제한이 걸려있는 것
HTTP 스펙이란?
- HTTP/1.1, HTTP/2 표준에는 “URL 최대 길이”를 강제하는 조항이 없다
- 프로토콜 자체로는 이론상 매우 긴 URL 전송 가능
Spring boot(Tomcat)
- Spring Boot 기본 내장 Tomcat은 maxHttpHeaderSize가 8KB로 설정
public AbstractHttp11Protocol(AbstractEndpoint<S, ?> endpoint) {
super(endpoint);
this.continueResponseTiming = ContinueResponseTiming.IMMEDIATELY;
this.useKeepAliveResponseHeader = true;
this.relaxedPathChars = null;
this.relaxedQueryChars = null;
this.allowHostHeaderMismatch = false;
this.rejectIllegalHeader = true;
this.maxSavePostSize = 4096;
this.maxHttpHeaderSize = 8192; // 이 친구
this.maxHttpRequestHeaderSize = -1;
this.maxHttpResponseHeaderSize = -1;
this.connectionUploadTimeout = 300000;
this.disableUploadTimeout = true;
this.restrictedUserAgents = null;
this.serverRemoveAppProvidedValues = false;
this.maxTrailerSize = 8192;
this.maxExtensionSize = 8192;
this.maxSwallowSize = 2097152;
this.allowedTrailerHeaders = ConcurrentHashMap.newKeySet();
this.upgradeProtocols = new ArrayList();
this.httpUpgradeProtocols = new HashMap();
this.negotiatedProtocols = new HashMap();
this.upgradeProtocolGroupInfos = new ConcurrentHashMap();
this.setConnectionTimeout(60000);
}
- URL + 헤더 전체 크기가 8KB를 넘으면 HTTP 400(Bad Request) 발생
- GET 요청의 쿼리 파라미터도 URL에 포함되므로, 길이가 길어지면 이 제한에 걸릴 수 있음
- 변경하려면 application.properties에
server.max-http-header-size=16384 # 16KB로 변경
예제
- 9byte → URL
DTO 객체 활용
DTO란? DTO는 Data Transfer Object의 약자로, 다른 레이어 간의 데이터 교환에 활용
- 간략하게 → 각 클래스 및 인터페이스를 호출하면서 전달하는 매개변수로 사용되는 데이터 객체
DTO는 데이터 교환하는 용도로만 사용, DTO에는 별도의 로직이 포함 X
6장에서 좀 더 다루기
public class MemberDto {
private String name;
private String email;
private String organization;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getOrganization() {
return organization;
}
public void setOrganization(String organization) {
this.organization = organization;
}
@Override
public String toString() {
return "MemberDTO{" +
"name='" + name + '\\'' +
", email='" + email + '\\'' +
", organization='" + organization + '\\'' +
'}';
}
}
- DTO 클래스에는 전달하고자 하는 필드 객체를 선언하고 게터/세터(getter/setter) 메서드를 구현한다.
- 선언된 필드는 컨트롤러의 메서드에서 쿼리 파라미터의 키와 매핑된다.
- 즉 쿼리스트링의 키가 정해져있지만 받아야할 파타미터가 많을 경우 위와 같이 DTO 객체 활용
// <http://localhost:8080/api/v1/get-api/request3?name=value1&email=value2&organization=value3>
@GetMapping(value = "/request3")
public String getRequestParam3(MemberDto memberDTO) {
return memberDTO.toString();
}
반응형
'Spring Boot > API를 작성하는 다양한 방법' 카테고리의 다른 글
[Spring boot] REST API 명세 문서화 (0) | 2025.08.14 |
---|---|
[Spring boot] DELETE API 만들기 (0) | 2025.08.14 |
[Spring boot] PUT API 만들기 (0) | 2025.08.14 |
[Spring boot] POST API 만들기 (3) | 2025.08.14 |
[Spring boot] API를 작성하는 다양한 방법을 공부하기 전 큰 틀 (1) | 2025.08.14 |