Back-End/Spring Boot

[Spring] - @REST Controller에서 사용되는 어노테이션

LightSource 2022. 7. 2. 17:56

스프링의 어노테이션들

@SpringBootApplication    //SpringBootApplication으로 설정
@RestController           //REST API를 제공하는 controller로 설정
@RequestMapping           //URL주소를 맵핑
@GetMapping               //Http GetMethod URL 주소 맵핑
@PostMapping              //Http PostMethod URL 주소 맵핑
@PutMapping               //Http PutMethod URL 주소 맵핑
@DeleteMapping            //Http DeleteMethod URL 주소 맵핑
@RequestParam             //URL Query Parameter 맵핑
@RequestBody              //Http Body를 Parsing 맵핑
@Valid                    //POJO java class의 검증
@Component                //1기의 Class단위로 등록할때 사용
@EnableJpaAuditing
@Aspect                   //AOP 적용시 사용
@Before                   //AOP 메서드 이전 호출 지정
@After                    //AOP 메서드 호출 이후 지정 예외 발생포함
@AfterReturning           //AOP 메서드의 호출이 정상일때 실행

@Entity
@EntityListeners(AuditingEntityListener.class)
@Repository
@Service

Spring MVC 어노테이션

1. @RestController

  • 이 어노테이션을 사용시 해당 컨트롤러 메서드는 @ResponseBody 어노테이션이 달린 반환 값을 달고 다닌다.
  • REST API설계시 필수적으로 사용하게 된다.
  • @GetMapping Http GetMethod URL 주소 맵핑 → 조회
    @PostMapping Http PostMethod URL 주소 맵핑 → 등록
    @PutMapping Http PutMethod URL 주소 맵핑 → 수정, 등록
    @DeleteMapping Http DeleteMethod URL 주소 맵핑 → 삭제
  • ModelAndView같은 유형은 스프링이 평소 그대로 처리하여 응답해준다.
//요청 url : http://localhost:9090/developer
// json Data : {
//        "name":"steve",
//        "age":"30",
//        "email":"steve@naver.com"
//        }

@RestController
public class DeveloperController{
    // 등록    POST
    @PostMapping("/developer")
    public void registerDeveloper(
        @RequestBody    DeveloperDto dto
    ){
        service.registerDeveloper(dto);
    }            
    // 수정    PUT
    @PutMapping("/developer/{name}")
    public void modifyDeveloper(
        @RequestBody    DeveloperDto dto,
        @PathVariable String name
    ){
        service.modifyDeveloper(dto,name);
    }        
    // 삭제    DELETE
    @DeleteMapping("/developer/{name}")
    public void removeDeveloper(
        @PathVariable String name
    ){
        service.removeDeveloper(name);
    }        
    // 상세조회 GET
    ****@GetMapping("/develo**p**er/{name}")
    public DeveloperDto findDeveloperDetail(
        @PathVariable String name
    ){
        return service.findDeveloperDetail(name);
    }    
    // 목록조회 GET
    @GetMapping("/developers")    
    public List<DeveloperDto> findDeveloperList(){
        return service.findDeveloperList();
    }
}

2. @RequstParam

  • 컨트롤러 메소드 인자에서 요청값을 받을때, URL에 ? 뒤로 시작하는 키/값 등을 받을 수 있다.
  • required = true 인 경우 파라미터 없이 호출 될 경우 404 Bad Request응답을 뱉는다.
// 요청 url : http://localhost:9090/api/get/query-param2?user=steve&email=steve@gmail.com&age=35

@RestController
@RequestMapping("/api/get")
public class GetApiController{
    @GetMapping("/query-param2")
    public String queryParam(
            @RequestParam String name,
            @RequestParam String email,
            @RequestParam int age
    ){
        return name+" "+email+" "+age;
    }
}

3. @PathVariable

  • URL에 있는 동적인 Parameter값을 가져오고 싶을때 사용가능하다.
// 요청 url : http://localhost:9090/api/get/path-variable/{name}

@RestController
@RequestMapping("/api/get")
public class GetApiController{
    @GetMapping("/path-variable/{name}")
    public String hello(
            @PathVariable String name;
    ){
        return name;
    }
}

4. @ResponseBody

  • 응답 객체를 클라이언트가 요구하는 Content-Type에 따라 응답하도록 도와주는 어노테이션
  • 보통은 Jackson모듈에 의해서 json유형으로 응답하며, 경우에 따라 응답 유형을 mimeType에 따라 설정 가능하다.
//ResponseBody로 받기위한 객체 모델링
@Getter
@Setter
@ToString
public class PostRequestDto{
    private String account;
    private String email;
    private String address;
    private String password;
}
//요청 url : http://localhost:9090/api/post/
//        BODY
//        {
//        "account":"user01",
//        "email":"steve@gmail.com",
//        "address":"스티브의 집",
//        "password":"abcd"
//        }

@RestController
@RequestMapping("/api")
public class PostApiController{
    @PostMapping("/post")
    public void post(
            @RequestBody PostRequestDto requestDto
    ){
        System.out.println(requestDto);
    }
}

참고

https://dev.to/composite/-40c0

반응형