1.RequestMapping이란?
- 특정 url로 요청을 보내면 Controller에서 어떤 방식으로 처리할지 정의하는데, 이 때 들어온 요청을 특정 메서드와 매핑하기 위해 사용하는 것이 @RequestMapping이다.
2. 예시
@RequestMapping(value = "/hello", method = RequestMethod.GET)
- method는 어떤 요청으로 받을 지 정의함(GET, POST, PUT, DELETE 등)
3. 메소드 단위 지정/ 클래스 단위 지정
1) 메소드 단위 지정
- 다음과 같이 메소드 단위로 RequestMapping을 지정하게 되면 같은값이 중복되고 불필요한 코드를 반복한다는 느낌이 든다.
@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(...) {
...
}
}
2) 클래스 단위 지정
- 다음과 같이 클래스에 RequestMapping을 지정하고, 각 메서드에는 @GetMapping, @PostMapping, @PutMapping, @DeleteMapping을 사용하므로써 간단하게 생략이 가능하다.
@RestController
@RequestMapping(value = "/hello")
public class HelloController {
@GetMapping()
public String helloGet(...) {
...
}
@PostMapping()
public String helloPost(...) {
...
}
@PutMapping()
public String helloPut(...) {
...
}
@DeleteMapping()
public String helloDelete(...) {
...
}
}
3) 두개 다 지정
- helloGetHi에 접근하기 위해서는 /hello/hi로 url을 매핑해줘야 한다.
@RestController
@RequestMapping(value = "/hello")
public class HelloController {
@GetMapping("/hi")
public String helloGetHi(...) {
...
}
}
'FrameWork > Spring' 카테고리의 다른 글
[Spring] 빌드 관리 도구 (0) | 2023.07.31 |
---|---|
[Spring] 의존성 주입 (0) | 2022.01.05 |
[Spring] 파일업로드, 다운로드 구현 (0) | 2020.12.12 |
[Spring] 쿠키, 세션 사용법 (0) | 2020.12.12 |
[Spring] 초기설정 (0) | 2020.12.12 |