인텔리제이와 자바11을 설치
RestController와 RequestMapping를 사용해서 간단하게 컨트롤러를 만들 수 있다.
@RestController
@RequestMapping("/api/v1/get-api")
public class GetController {
}
프로젝트 수준에서 @RequestMapping을 사용하면 공통 url을 추가할 수 있다.
위 hello 예제처럼 메서드에 @RequestMapping을 쓰면 http의 모든 요청을 받으나...
스프링 4.3 버전 이후로는 각 http 메서드에 맞는 어노테이션을 사용하는게 바람직하다.
- @GetMapping
- @PostMapping
- @PutMapping
- @DeleteMapping
GET API 만들기
매개변수가 없는 GET 메서드
@GetMapping(value = "/name")
public String getName() {
return "Flature";
}
간단함.
@PathVariable 활용
@GetMapping(value = "/variable1/{variable}")
public String getVariable1(@PathVariable String variable) {
return variable;
}
url에 값을 담아 전달한다.
@GetMapping 의 중괄호 변수명과 @PathVariable 어노테이션을 맞춰줘야 한다.
@GetMapping(value = "/variable2/{variable}")
public String getVariable2(@PathVariable("variable") String var) {
return var;
}
어려운 경우 @PathVariable 안에 괄호를 붙여 어노테이션의 변수명을 지정한다.
@RequestParam 활용
@GetMapping(value = "/request1")
public String getRequestParam1(
@RequestParam String name,
@RequestParam String email,
@RequestParam String organization) {
return name + " " + email + " " + organization;
}
여러 값을 url에 ?와 &를 붙여 전달하는 방식
매개변수의 항목이 일정하지 않다면 Map 객체로 받을 수 있다.
@GetMapping(value = "/request2")
public String getRequestParam2(@RequestParam Map<String, String> param) {
StringBuilder sb = new StringBuilder();
param.entrySet().forEach(map -> {
sb.append(map.getKey() + " : " + map.getValue() + "\n");
});
return sb.toString();
}
DTO 객체를 활용한 GET 메서드 구현
// 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();
}
객체 MeberDto를 파라미터로 받고 싶다면 이런식으로 구현할 수 있다.
@RequestParam을 일일히 쓰지 않아도 되어 간편하다.
POST API 만들기
url의 경로에 변수를 넣는 get api와 다르게 post api는 값을 http body에 담아 전달한다.
@PostMapping(value = "/member")
public String postMember(@RequestBody Map<String, Object> postData) {
StringBuilder sb = new StringBuilder();
postData.entrySet().forEach(map -> {
sb.append(map.getKey() + " : " + map.getValue() + "\n");
});
return sb.toString();
}
// http://localhost:8080/api/v1/post-api/member2
@PostMapping(value = "/member2")
public String postMemberDto(@RequestBody MemberDto memberDTO) {
return memberDTO.toString();
}
@RequestBody를 통해 값을 전달할 수 있다.
만약에 toString 없이 그냥 객체를 리턴하면 json 형식으로 받을 수 있다.
PUT API 만들기
@PutMapping을 쓴다는 것을 빼면 post api와 거의 유사하다.
@RequestBody로 파라미터를 받아 로직을 처리한다.
별 특별할게 없으니 겸사겸사 @PutMapping 을 활용하여
다른 Http 메서드에서도 동일하게 사용할 수 있는 ResponseEntity를 써보자.
@PutMapping(value = "/member3")
public ResponseEntity<MemberDto> postMemberDto3(@RequestBody MemberDto memberDto) {
return ResponseEntity
.status(HttpStatus.ACCEPTED)
.body(memberDto);
}
이렇게 ResponseEntity<객체>를 활용하면 응답 코드 변경은 물론 헤더와 바디를 더욱 쉽게 구성할 수 있다.
DELETE API 만들기
@DeleteMapping은 @GetMapping과 유사하다.
@PathVariable와 @RequestParam을 활용하여 삭제할 값을 url로 받을 수 있다.
Swagger
api 명세 관리 툴이다.
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.springboot.api"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot Open API Test with Swagger")
.description("설명 부분")
.version("1.0.0")
.build();
}
}
의존성을 추가하고 config 패키지를 만들어 SwaggerConfiguration 클래스를 추가한다.
@ApiOperation(value = "GET 메소드 예제", notes = "@RequestParam을 활용한 GET Method")
@GetMapping(value = "/request1")
public String getRequestParam1(
@ApiParam(value = "이름", required = true) @RequestParam String name,
@ApiParam(value = "이메일", required = true) @RequestParam String email,
@ApiParam(value = "회사", required = true) @RequestParam String organization) {
return name + " " + email + " " + organization;
}
그리고 메서드에 api 에 대한 설명을 붙인다.
그러면 localhost:8080/swagger-ui.html 페이지에서 간편하게 확인할 수 있다.
Logback
private final Logger LOGGER = LoggerFactory.getLogger(GetController.class);
@GetMapping(value = "/name")
public String getName() {
LOGGER.info("getHello 메소드가 호출되었습니다.");
return "Flature";
}
디버깅할때 System.out.println을 쓰는건 하수다...
resource 폴더 아래에 logback-spring.xml 을 추가하면 Logback으로 로깅을 할 수 있다.
'개발 관련 공부 > 스프링부트 핵심 가이드' 카테고리의 다른 글
06 데이터베이스 연동(3) (0) | 2023.10.28 |
---|---|
06 데이터베이스 연동(2) (2) | 2023.10.14 |
06 데이터베이스 연동(1) (0) | 2023.10.03 |
02 개발에 앞서 알면 좋은 기초 지식 (0) | 2023.10.01 |
01 스프링 부트란? (0) | 2023.09.30 |
댓글