@RequestMapping 에 대해서

Today Jeeho Learned·2022년 6월 28일
0

Spring

목록 보기
20/31

RequestMapping 요청 매핑이란 ?

요청이 왔을 때 어떤 컨트롤러가 호출이 되어야 하는지 알려주는 지표 같은 것이다.

value 방식

@RequestMapping(value = "/hello-basic")

이렇게 매핑을 하면 localhost:8080/hello-basic으로 url을 입력했을 경우에 이것에 해당하는 메서드가 실행된다.

@RequestMapping은 다중요청도 가능하다!

다중 요청을 하려면 배열로 묶어야 한다.

@RequestMapping(value = {"/hello", "/hello-basic"})

이것처럼 다중 요청을 할 경우에는 둘 중 아무url이나 입력해도 된다.

경로 변수 PathVariable 사용

최근 HTTP API는 리소스 경로에 식별자를 넣는 스타일을 선호한다.

쿼리 파라미터로 식별자를 넣는 방법도 있지만 경로 변수를 사용하는 것이 매핑되는 부분을 편리하게 조회할 수 있다.

@GetMapping("/mapping/{userId}")
    public String mappingPath(@PathVariable("userId") String data) {
        log.info("mappingPath userId={}", data);
        return "ok";
    }

localhost:8080/mapping/userA 이라는 url을 입력하면 userId가 data로 매핑돼서 편하게 사용할 수 있다.

    @GetMapping("mapping/{userId}")
    public String mappingPath(@PathVariable String userId) {
        log.info("mappingPath userId={}", userId);
        return "ok";
    }

@PathVariable 어노테이션을 선언한 "userId"는 String 자료형으로 data에 매핑이 되는데, 아래와 같이 data 대신 같은 파라미터를 선언해주면 생략이 가능하다.

	@GetMapping("/mapping/users/{userId}/orders/{orderId}")
    public String mappingPath(@PathVariable String userId, @PathVariable Long orderId) {
        log.info("mappingPath userId={}, orderId={}", userId, orderId);
        return "ok";
    }

다중으로도 사용 가능하다.

method

RequestMethod의 경우, GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE 등 8가지가 있다. 보통의 경우에는 @RequestMapping 어노테이션에 아래와 같이 method를 쓸 수 있다.

@RequestMapping(method = RequestMethod.GET, value = "/hello")

하지만 GET, POST, PUT, PATCH, DELETE 메서드에 대해서 각각에 맞는 메서드 옵션이 적용된 어노테이션(@GetMapping이나 @PostMapping과 같은)이 존재하여 @RequestMapping 하위에 써서 코드를 좀 더 간결하게 만들 수 있다.

출처
https://velog.io/@dyunge_100/Spring-%EC%9A%94%EC%B2%AD-%EB%B0%A9%EC%8B%9DRequestMapping-GetMapping-PostMapping

profile
기록해야 (살아)남는다 !

0개의 댓글