이론을 싫어!

@GetMapping , @PostMapping 에 대해 알아봅시다! 본문

Spring and Springboot

@GetMapping , @PostMapping 에 대해 알아봅시다!

이론을 싫어! 2023. 3. 13. 23:46
반응형

@GetMapping 과 @PostMapping 은 Get 방식으로 요청이 오는지 아니면 

 

Post방식으로 요청이 오는지에 따라서 정해준다. 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Controller
public class RegisterController{
 // @RequestMapping(value="/register/add" , RequestMethod.GET)  아래 @GetMapping와 같다.  
   @GetMapping("/register/add")
    public String register(){
 
       return "registerForm";
 }
 
 // @RequestMapping(value="/register/add" , RequestMethod.POST)  아래 @PostMapping와 같다.  
   @PostMapping("/register/add")
    public String save(User user, Model m) throws Exception{
  if(!isValid(user)){
      String msg=URLEncoder.encode("id를 잘못입력하셨습니다." , "utf-8");
 
       m.addAttribute("msg",msg);
           return "redirect:/register/add"; // redirect는 재요청의 의미를 가지고 있다.
 }
 
  return "registerInfo"
}
cs

 

@GetMapping 이랑 @PostMapping 쓰는 법이다.

 

물론 @RequestMapping 으로 써도 되지만 @GetMapping 또는 @PostMapping 으로 쓰는것이 더 간단 하다.

 

위의 코드를 좀 설명을 좀 하면 

 

registerForm 의 메소드는 get방식으로 요청이 들어왔을때 처리하는 메소드 이며,

 

save의 메소드는 Post 방식으로 요청이 들어왔을떄 처리하는 메소드이다. 

 

우리가 GetMapping 이랑 PostMapping의 방식을 배우기 전에는 URL 같으면 충돌 나지만 

 

Get 과 Post의 방식은 다르기 때문에 충돌이 나지 않는다 .

 

그러면 이제 RequestMapping 은 안쓰나?? 

 

꼭 그렇지 않다. 밑의 코드를 보자 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Controller
@RequestMapping("/register")
public class RegisterController{
 // @RequestMapping(value="/register/add" , RequestMethod.GET)  아래 @GetMapping와 같다.  
   @GetMapping("/add")
    public String register(){
 
       return "registerForm";
 }
 
 // @RequestMapping(value="/register/add" , RequestMethod.POST)  아래 @PostMapping와 같다.  
   @PostMapping("/add")
    public String save(User user, Model m) throws Exception{
  if(!isValid(user)){
      String msg=URLEncoder.encode("id를 잘못입력하셨습니다." , "utf-8");
 
       m.addAttribute("msg",msg);
           return "redirect:/register/add";
 }
 
  return "registerInfo"
}
cs

 

RequestMapping으로 중복된 부분을 클래스에 적용시켜준 부분이다.

 

즉, 클라이언트에서 http://localhost:8080/ch2/register 라고 요청이 들어오면 위의 클래스에 요청이 들어온것이다.