자바/Spring

Spring MVC

끄적끄적 2022. 3. 18. 11:33

Controller 매핑

@RequestMapping(value = "/mapping-get-v1", method = RequestMethod.GET)
@GetMapping(value = "/mapping-get-v2")
/**
 * PathVariable 사용
 * 변수명이 같으면 생략 가능
 *
 * @PathVariable("userId") String userId -> @PathVariable String userId
 * /mapping/userA
 */
@GetMapping("/mapping/{userId}")
public String mappingPath(@PathVariable("userId") String data) {
    log.info("mappingPath userId={}", data);
    return "ok";
}
/**
 * PathVariable 사용 다중
 */
@GetMapping("/mapping/users/{userId}/orders/{orderId}")
public String mappingPath(@PathVariable String userId, @PathVariable Long orderId) {
    log.info("mappingPath userId={}, orderId={}", userId, orderId);
    return "ok";
}

요청 파라미터 vs HTTP 메시지 바디
- 요청 파라미터를 조회하는 기능: @RequestParam , @ModelAttribute
- HTTP 메시지 바디를 직접 조회하는 기능: @RequestBody

- 스프링은 @ModelAttribute , @RequestParam 해당 생략시 다음과 같은 규칙을 적용한다.
   String , int , Integer 같은 단순 타입 = @RequestParam
   나머지 = @ModelAttribute (argument resolver 로 지정해둔 타입 외)

- 파라미터변수는 하이픈, 스네이크케이스인데, 자바변수는 카멜케이스 : @RequestParam("user_id")와 같이 사용
- @RequestBody의 경우 @JsonProperty 또는 @SerializedName 사용해서 치환

@ResponseBody
@ResponseBody 를 사용하면 응답 결과를 HTTP 메시지 바디에 직접 담아서 전달할 수 있다.

 

 

@RequestParam URL 의 Query Parameter 를 Parsing 할때 사용 url : https://foo.co.kr?id=1 ,
ex) public Student create(@RequestParam Long id)
Object Query Parameter를 Object로 바로 맵핑할때 사용 https://foo.co.kr?id=1 ,
ex) public Student create(Student student)
@PathVariable URL 의 Path의 값을 Parsing 할때 사용 https://foo.co.kr/1 ,
ex) @GetMapping("/{id}" public Optional read(@PathVariable Long id)
@RequestBody Http Method의 POST, PUT의 BODY를 Parsing할때 사용 https://foo.co.kr

 

반응형