package com.springboot.api.controller;
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";
}
}
package com.springboot.api.controller;
import org.springframework.web.bind.annotation.GetMapping;
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 {
//매개 변수가 없는 GET 메서드 구현
@GetMapping(value = "/name")
public String getName(){
return "Flature";
}
}
package com.springboot.api.controller;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/get-api")
public class GetController {
// @PathVariable을 활용한 GET 메서드 구현 -> {String 값}
@GetMapping(value = "/variable1/{variable}")
public String getVariable1(@PathVariable String variable){
return variable;
}
}
package com.springboot.api.controller;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/get-api")
public class GetController {
// @PathVariable에 변수명을 매핑하는 방법
@GetMapping(value = "/variable2/{variable}")
public String getVariable2(@PathVariable("variable") String var){
return var;
}
}
package com.springboot.api.controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.annotation.RequestScope;
@RestController
@RequestMapping("/api/v1/get-api")
public class GetController {
//@RequestParam을 활용한 GET 메서드 구현
@GetMapping(value = "/request1")
public String getRequestParam1(
@RequestParam String name,
@RequestParam String email,
@RequestParam String organization) {
return name + " " + email + " " + organization;
}
}
package com.springboot.api.controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.annotation.RequestScope;
import java.util.Map;
@RestController
@RequestMapping("/api/v1/get-api")
public class GetController {
//@RequestParam과 Map을 조합한 GET 메서드 구현
@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();
}
}
package com.springboot.api.controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.annotation.RequestScope;
import java.util.Map;
@RestController
@RequestMapping("/api/v1/get-api")
public class GetController {
// DTO 객체를 활용한 GET 메서드 구현
@GetMapping(value = "request3")
public String getRequestParam3(MemberDTO memberDTO) {
return memberDTO.toString();
}
}
package com.springboot.api.dto;
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 + '\'' +
'}';
}
}
package com.springboot.api.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/post-api")
//컨트롤러 클래스에서 공통 URL 설정
public class PostController {
}
package com.springboot.api.controller;
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/post-api")
//컨트롤러 클래스에서 공통 URL 설정
public class PostController {
//@RequestMapping으로 구현하기
@RequestMapping(value = "/domain", method = RequestMethod.POST)
public String postExample() {
return "Hello Post API";
}
}
package com.springboot.api.controller;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@RequestMapping("/api/v1/post-api")
public class PostController {
//@RequestBody를 활용한 POST 메서드 구현
@PostMapping("member")
public String postMember(
@RequestBody Map<String, String> postData
){
StringBuilder sb = new StringBuilder();
postData.entrySet().forEach(
map -> {
sb.append(map.getKey() + " : " + map.getValue() + "\n");
}
);
return sb.toString();
}
}
package com.springboot.api.controller;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping("/api/v1/put-api")
public class PutController {
//@RequestBody와 Map을 활용한 PUT 메서드 구현
@PutMapping(value = "/member")
public String postMemver(@RequestBody Map<String, Object> putData) {
StringBuilder sb = new StringBuilder();
putData.entrySet().forEach(map -> {
sb.append(map.getKey() + " : " + map.getValue() + "\n");
});
return sb.toString();
}
}
package com.springboot.api.controller;
import com.springboot.api.dto.MemberDTO;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping("/api/v1/put-api")
public class PutController {
//DTO 객체를 활용한 PUT 메서드 구현 - String 리턴
@PutMapping(value = "/member1")
public String postMemberDTO1(@RequestBody MemberDTO memberDTO){
return memberDTO.toString();
}
//DTO 객체를 활용한 PUT 메서드 구현 - memberDTO 리턴
@PutMapping(value = "/member2")
public MemberDTO postMemberDTO2(@RequestBody MemberDTO memberDTO){
return memberDTO;
}
}
package com.springboot.api.controller;
import com.springboot.api.dto.MemberDTO;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping("/api/v1/put-api")
public class PutController {
//ResponseEntity를 활용한 PUT 메서드 구현
@PutMapping(value = "/member3")
public ResponseEntity<MemberDTO> postMemberDTO3(@RequestBody MemberDTO memberDTO){
return ResponseEntity
.status(HttpStatus.ACCEPTED)
.body(memberDTO);
}
}
package com.springboot.api.controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/delete-api")
public class DeleteController {
//@PathVariable과 @RequestParam을 활용한 DELETE 메서드 구현
@DeleteMapping(value = "/{variable}")
public String DeleteVariable(@PathVariable String variable){
return variable;
}
}
package com.springboot.api.controller;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/delete-api")
public class DeleteController {
//@RequestParam을 활용한 DELETE 메서드 구현
@DeleteMapping(value = "request1")
public String getRequestParam1(@RequestParam String email){
return "e-mail : " + email;
}
}
//SWAGGER
implementation 'io.springfox:springfox-boot-starter:3.0.0'
implementation 'io.springfox:springfox-swagger-ui:3.0.0'
package com.springboot.api.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
@EnableWebMvc
public class SwaggerConfig {
@Bean
public Docket restAPI() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("groupName1")
.select()
.apis(RequestHandlerSelectors.
basePackage("com.springboot.api"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot Open API Test with Swagger")
.version("1.0.0")
.description("Back to Spring API 명세서입니다.")
.build();
}
}
...
// @RequestParam을 활용한 GET 메서드 구현
@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;
}
...
slf4j
ERROR : 로직 수행 중 시스템에 심각한 문제가 발생해 애플리케이션의 작동이 불가능한 경우를 의미
WARN : 시스템 에러의 원인이 될 수 있는 경고 레벨을 의미
INFO : 애플리케이션의 상태 변경과 같은 정보 전달을 위해 사용
DEBUG : 애플리케이션의 디버깅을 위한 메시지를 표시하는 레벨을 의미
TRACE : DEBUG 레벨보다 더 상세한 메시지를 표현하기 위한 레벨을 의미
resorce > logback-spring.xml 파일을 참조하도록 생성
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<property name="LOG_PATH" value="./logs"/>
<!-- Appenders -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>INFO</level>
</filter>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level] [%thread] %logger %msg%n</pattern>
</encoder>
</appender>
<appender name="INFO_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>INFO</level>
</filter>
<file>${LOG_PATH}/info.log</file>
<append>true</append>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_PATH}/info_%d{yyyy-MM-dd}.log.gz</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level] [%thread] %logger %msg%n</pattern>
</encoder>
</appender>
<!-- TRACE < DEBUG < INFO < WARN < ERROR < OFF -->
<!-- Root Logger -->
<root level="INFO">
<appender-ref ref="console"/>
<appender-ref ref="INFO_LOG"/>
</root>
</configuration>
//예시
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level] [%thread] %logger %msg%n</pattern>
<root level="INFO">
<appender-ref ref="console"/>
<appender-ref ref="INFO_LOG"/>
</root>
<!-- 또는 -->
<logger name="com.springboot.api.controller" level="DEBUG" additivity="false">
<appender-ref ref="console"/>
<appender-ref ref="INFO_LOG"/>
</logger>
...
@RestController
@RequestMapping("/api/v1/get-api")
public class GetController {
//Logback 적용하기
private final Logger LOGGER = LoggerFactory.getLogger(GetController.class);
...
...
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String getHello() {
LOGGER.info("getHello 메서드가 호출되었습니다.");
return "Hello World";
}
// 매개 변수가 없는 GET 메서드 구현
@GetMapping(value = "/name")
public String getName(){
LOGGER.info("getName 메서드가 호출되었습니다.");
return "Flature";
}
...
...
@GetMapping(value = "/variable1/{variable}")
public String getVariable1(@PathVariable String variable){
LOGGER.info("@PathVariable을 통해 들어온 값 : {}", variable);
return variable;
}
...