Spring Annotation (2)

원종운·2019년 12월 29일
2

Spring Annotation

@RequestParam

  • GET 요청으로 넘어오는 Parameter를 Method의 해당 Annotation을 사용한 Parameter에 매핑하여 줍니다.
    + @RequestParam Annotation의 value(name)와 1:1 매핑되며, 생략시 변수명과 1:1 매핑됩니다.
  • Parameter가 생략될 경우 Exception이 발생합니다.
  • 필수가 아닌 Parameter에 대해서는 required, defaultValue를 사용하여 예외를 방지할 수 있습니다.

name과 value의 차이

  • 기능적으로 동일하며 어느 것을 사용하든 동일한 기능을 사용할 수 있습니다.
  • 두 개 모두 사용할 경우 동일한 값으로 사용하여야 합니다.
  • 올바른 사용 예
@RequestParam(value="param1", required=true) 
// name, value 모두 동일한 기능을 합니다.
@RequestParam(name="param1", required=true) 
// name, value 모두 동일한 기능을 합니다.
@RequestParam(value="param1", required=true, name="param1") 
// name, value 두개를 사용할 경우 동일한 값이여야 합니다.
  • 잘못된 사용 예
@RequestParam(value="param1", required=true, name="param3" 
// value와 name의 값이 다르므로 잘못된 사용 방법입니다.

@PathVariable

  • '/' 구분자 단위로 넘어오는 Parameter를 Method의 해당 Annotation을 사용한 Parameter에 매핑하여 줍니다.
  • @PathVariable Annotation의 value(name)과 1:1 매핑되며, 생략시 변수명과 1:1 매핑됩니다.
  • GetMapping, PostMapping, PutMapping, DeleteMapping의 요청 경로에 {variable}로 선언하여 줍니다.
    • GetMapping("/request/{id}")
  • Parameter가 생략될 경우 Exception이 발생합니다.
    • @RequestParam처럼 required, defaultValue가 따로 존재하지 않으므로 생략된 경로, 그렇지 않은 경로 모두 처리를 해주어야합니다.
@GetMapping({"/request/{id}", "/request/"}) // 생략된 경로, 그렇지 않은 경로 모두 처리
public String requestParam(@PathVariable Optional<String> id) {
	return id.orElse("null"); // Optional을 사용하여 생략된 경우, 그렇지 않은 경우 나눠서 처리
}

@ResponseBody

  • method의 반환 값을 HTTP Response Body에 직접 쓰여지게 해줍니다.
    • MessageConverter에 의하여 쓰여지는 형식이 결정되어집니다. ( 기본은 JSON )

@RestController

  • Controller의 모든 method에 @ResponseBody Annotation을 달아주는 것과 동일한 효과가 나타나게 해줍니다.
  • @RestController = @Controller + @ResponseBody

@RequestMapping

  • HTTP Method의 요청을 받아서 처리할 수 있도록 하여 줍니다.
    • HTTP Method 중 GET 요청을 받아서 처리할 수 있도록 하는 예
      • @RequestMapping(method = RequestMethod.GET)
    • HTTP Method 중 POST 요청을 받아서 처리할 수 있도록 하는 예
      • @RequestMapping(method = RequestMethod.POST)
    • HTTP Method 중 PUT 요청을 받아서 처리할 수 있도록 하는 예
      • @RequestMapping(method = RequestMethod.PUT)
    • HTTP Method 중 DELETE 요청을 받아서 처리할 수 있도록 하는 예
      • @RequestMapping(method = RequestMethod.DELETE)

@GetMapping

  • HTTP Method 중 GET 요청을 받아서 처리할 수 있도록 하여줍니다.
  • @GetMapping = @RequestMapping(method = RequestMethod.GET)

@PostMapping

  • HTTP Method 중 POST 요청을 받아서 처리할 수 있도록 하여줍니다.
  • @PostMapping = @RequestMapping(method = RequestMethod.POST)

@PutMapping

  • HTTP Method 중 PUT 요청을 받아서 처리할 수 있도록 하여줍니다.
  • @PutMapping = @RequestMapping(method = RequestMethod.PUT)

@DeleteMapping

  • HTTP Method 중 DELETE 요청을 받아서 처리할 수 있도록 하여줍니다.
  • @DeleteMapping = @RequestMapping(method = RequestMethod.DELETE)

참고 자료

profile
Java, Python, JavaScript Lover

0개의 댓글