Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Tags
more
Archives
Today
Total
관리 메뉴

개발자 도전기

[Spring] 핸들러(Handler) - @RequestParam, @ModelAttribute 본문

개발공부/Spring

[Spring] 핸들러(Handler) - @RequestParam, @ModelAttribute

jnnjnn 2024. 4. 16. 23:49

 

핸들러란?

스프링에서 @Controller 어노테이션이 붙은 클래스를 컨트롤러라고 한다.

이 컨트롤러 안에서 요청을 처리하는 메소드가 핸들러이다

 

 

핸들러 매핑

@RequestMapping

@RequesstMapping 어노테이션을 사용하면 요청 uri을 핸들러에 매핑시킬 수 있다.

// /sub7 경로 요청에 매핑
@RequestMapping("sub7")
public void handler(){ }

 

Http Method

  • HTTP는 GET, POST, PUT , PATCH, DELETE 와 같은 요청 메소드를 가진다.
  • 특정 요청 메소드에만 비즈니스 로직을 실행할 수 있도록 @RequstMapping에 설정할 수 있다.
  • @RequestMapping(method = RequestMethod.GET) 와 같이 지정한다
  • @GETMapping 처럼 줄여서 쓸 수 있다
@RequestMapping(value = "sub7", method = RequestMethod.GET)
public void handler1(){ }
// 같은 경로상에 메소드만 다르게 가능
@RequestMapping(value = "sub7", method = RequestMethod.POST)
public void handler2(){ }

//다중으로 받는 것도 가능
@RequestMapping(value = "sub8", method = {RequestMethod.GET, RequestMethod.POST})

@GETMapping("sub9")
public void handler3(){ }

 

 

핸들러 메소드 아규먼트

핸들러 메소드 아규먼트는 요청에 들어있는 값 중 핸들러에서 사용하고 싶은 정보를 꺼내서 사용하는 개념이다

 

@RequestParam

요청값으로 전달된 uri의 쿼리문을 읽어온다.

@GetMapping("sub1")
public void method(@RequestParam String name,
		@RequestParam Integer age){
}

 

@RequestParam의 자세한 내용은 아래 글 참고

 

 

@ModelAttribute

  • 요청 파라미터를 자바 객체에 바인딩하는 데 사용된다
  • @RequestParam과 달리 복합 객체를 사용해서 여러 값을 받아올 수 있다
  • 자동으로 Model에 객체를 추가한다
@Getter
@Setter
public class Car {
	String model;
    String color;
    Integer price;
}
// /sub5?model=k5&color=white&price=500

@RequestMapping("sub5")
public void method(@ModelAttribute Car car){
	return car.getModel() + car.getColor() + car.getPrice();
}