Java/Spring framwork

controller에서 다양한 방식으로 파라미터 값 받기

휘휘o 2020. 7. 21. 10:46

1. @RequestParam(value = "name", required = "true", defaultValue = "none")

 

value => 파라미터 이름 변경  , required => 전달이 안되면 오류 발생, defaultValue => 디폴트 값 설정

 

각각 파라미터를 알맞는 형태로 받을 수 있다. 받은 값이 없다면 디폴트 값이 됌

 

ex)

@GetMapping(path="/products")
	public Map<String, Object> products(@RequestParam(defaultValue="0") int categoryId,
			@RequestParam(defaultValue="0") int start) {
		
		...

		return map;
	}

 

2. @PathVariable()

 

path에 설정한 {param} 대괄호 값을 넘겨받아 파라미터로 사용할 수 있다.

 

ex)

@GetMapping(path="/products/{displayInfoId}")
	public Map<String, Object> displayInfo(@PathVariable() int displayInfoId) {
		Map<String, Object> map = new HashMap();

		...
        
		return map;
	}

 

 

 

3. @ModelAttribute 

 

여러가지 파라미터를 넘겨 받을 때 사용한다. 똑같은 변수명을 가진 파라미터가 자동으로 매핑되어 편리하게 변수를 넘겨 받을 수 있다. 데이터형식, 이름이 똑같아야 매핑된다.

 

클라이언트에 넘겨 받을 데이터는 Query String으로 되어 있어야 한다.

 

 

4. @ RequestBody

 

파라미터를 Object형식으로 넘겨 받을 때 사용한다. 똑같은 변수명을 가진 파라미터가 매핑되어 편리하게 변수를 넘겨 받을 수 있다.

클라이언트에 넘겨 받을 때 데이터는 Json body형식으로 이루어져 있다.

 

ex)

@PostMapping(path="/reservations")

	public String reservations(@RequestBody ReservationParam reservationParam,
			HttpSession session,
			RedirectAttributes redirectAttr) {
		
        ...
        
		return "redirect/";
	}