본문 바로가기
Spring

@RequestMapping 이란?

by invelog 2023. 8. 24.
반응형

특정 URI로 요청을 보내게 되면 Controller에서는 이를 어떤 방식으로 처리할지 정의한다. 

이 경우 들어온 요청을 특정 메서드와 Mapping할 때 사용하는 어노테이션이 @RequestMapping이다. 

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

@RequestMapping의 속성은 많지만 주로 사용하는 것이 value와 method이다. 위와 같이 value 속성에는 요청 받을 URL을 작성하고 method는 어떤 방식(GET, POST, PUT, DELETE)으로 요청을 받을지 작성한다.

 

이때, /hello라는 동일한 URL로 GET, POST, PUT, DELETE 메서드를 작성해야 한다면 

@RestController
public class HelloController {

	@RequestMapping(value = "/hello", method = RequestMethod.GET)
    	public String helloGet(...) {
    		...
    	}
    
    	@RequestMapping(value = "/hello", method = RequestMethod.POST)
    	public String helloPost(...) {
    		...
    	}
    
    	@RequestMapping(value = "/hello", method = RequestMethod.PUT)
    	public String helloPut(...) {
    		...
    	}
    
    	@RequestMapping(value = "/hello", method = RequestMethod.DELETE)
    	public String helloDelete(...) {
    		...
    	}
}

와 같이 작성하겠지만 비효율적으로 보인다. 

 

@RestController
@RequestMapping(value = "/hello")
public class HelloController {
	
    @GetMapping()
    public String helloGet(...) {
    	...
    }
    
    @PosttMapping()
    public String helloPost(...) {
    	...
    }
    
    @PutMapping()
    public String helloPut(...) {
    	...
    }
    
    @DeleteMapping()
    public String helloDelete(...) {
    	...
    }
}

위와 같이 공통적인 URL은 클래스에 @RequestMapping으로 설정하면 각각의 메서드에 URL을 작성할 필요가 없게 된다. 

각각의 메서드에 추가적으로 URL을 사용하고 싶다면 

@RestController
@RequestMapping(value = "/hello")
public class HelloController {
	@GetMapping("/hi")
    public String helloGetHi(...) {
    	...
    }
}

와 같이 @GetMapping, @PostMapping, @PutMapping, @DeleteMapping 중 필요한 곳에 추가적으로 작성하면 된다. 

위에서 HelloGetHi에 들어가기 위해서는 /hello/hi URL로 들어가야 한다. 

 

여기서 알아두어야 할 점은 @RequestMapping은 클래스와 메서드에 붙일 수 있지만 @GetMapping, @PostMapping, @PutMapping, @DeleteMapping은 메서드에만 붙일 수 있다. 

 

 


 

참고 글

https://mungto.tistory.com/436

반응형

'Spring' 카테고리의 다른 글

Scheduler 처리  (1) 2023.10.26
VO에서 Map 변환 메서드 (Apache Util)  (2) 2023.08.31
@ModelAttribute 그리고 @RequestParam  (0) 2023.08.24
@Resource Annotation 이란?  (0) 2023.08.24
@Controller와 @RestController  (0) 2023.08.24