[스프링 부트 핵심 가이드] API 를 작성하는 다양한 방법

FeelingXD·2023년 3월 19일
0

북스터디

목록 보기
3/13
post-thumbnail

@RequestMapping 리퀘스트 매핑

@RestController
@RequestMapping("/api/v1/get-api")
{
	public class GetController{
    	@RequestMapping(value="/hello" ,method= RequestMethod.Get)
        public String getHello(){
        	return "Hello World";
        }
    }
}

@RequestMapping 어노테이션을 사용하는 방법이다. 단지 RequestMapping 어노테이션을 사용할경우 모든 method에 대해 응답을한다. method에 대한 응답을주려면 method 값으로 지정해주어야한다. 위의 예제는 GET 메소드를 이용하는 방법의 예시 이다.

하지만 스프링 4.3 버전이후로 새로나온 아래의 어ㅏ노테이션을 사용하기에 @RequestMapping 어노테이션은 더 이상 사용되지 않는다.


- @GetMapping :get메소드에  대한 응답
- @PostMapping : post메소드에 대한 응답
- @PutMapping : put메소드에 대한 응답
- @DeleteMapping : delete메소드에 대한 응답

매개변수를 넘겨주는 방법

@PathVariable 을 활용 한 GET


@GetMapping("/variable1/{variable}")
public String getVariable1(@PathVariable String variable){
	return variable;
}

/* localhost:8080/variable1/12345
	=> variable =12345
*/

@RequestParam 으로 매개변수 주기

@GetMapping("/request1")
public String getRequestParam1(
	@RequestParam String name,
    @RequestParam String email,
    @RequestParam String organization)
    {
    	return name+email+organization;
    }
)

/*
localhost:8080/request1?name=jimin&email=test@gmail.com&organization=company
name,email, organization 을 key value 형태로 매핑
*/
profile
tistory로 이사갑니다. :) https://feelingxd.tistory.com/

0개의 댓글