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

2022. 7. 2. 17:56·Back-End/Spring Boot

스프링의 어노테이션들

@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

반응형
'Back-End/Spring Boot' 카테고리의 다른 글
  • [SpringBoot] 인터셉터
  • SpringBoot - 초기화 과정, @SpringBootApplication
  • 빌드 관리 도구 - 메이븐(Maven)과 그래들(Gradle)
LightSource
LightSource
어제보단 발전한 오늘의 나를 위한 블로그
    반응형
  • LightSource
    LightSourceCoder
    LightSource
  • 전체
    오늘
    어제
    • 분류 전체보기 (152)
      • Git (4)
      • Language (6)
        • Java (6)
      • Back-End (63)
        • Spring Boot (4)
        • MyBatis (1)
        • Oracle (1)
        • PL SQL (3)
        • JPA (26)
        • Spring Data JPA (5)
        • Spring MVC (8)
        • Spring (12)
        • Spring Security (2)
        • Redis (1)
      • Front-End (38)
        • 아이오닉 (2)
        • JSP (7)
        • JavaScript (4)
        • React (16)
        • TypeScript (3)
        • Angular (6)
      • AWS (1)
      • CI & CD (1)
      • 개발지식 (13)
        • 네트워크 (9)
        • CS 지식 (4)
      • 데이터모델링 (2)
      • Tool (1)
      • 프로젝트 (5)
      • 독후감 (2)
      • 잡생각 (0)
      • 면접 준비 (1)
      • 알고리즘 (14)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    배열요소수정
    리액트
    배요소열추가
    배열요소삭제
    react
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
LightSource
[Spring] - @REST Controller에서 사용되는 어노테이션
상단으로

티스토리툴바