스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 (김영한) 강의 수강 후 정리한 자료입니다.

❗스프링 MVC 기본 기능: 로깅❗

✨ 요청 매핑

@RequestMapping

  • @RequestMapping에 url은 배열 형태로 관리되기 때문에 url을 여러 개 넣을 수도 있다.

PathVariable Style

  • url 경로에 값을 템플릿처럼 사용하도록 할 수 있는 것
@GetMapping("/mapping/{userId}")
public String mappingPath(@PathVariable("userId") String data) {
    log.info("mappingPath userId={}", data);
    return "ok";
}

userId 값은 수시로 바뀔 수 있기 때문에 이를 path에서 뽑아내어 바로 사용하는 것이 훨씬 간편하다.

또한, @PathVariable의 경로명과 이름이 같으면 생략도 가능하다.

@GetMapping("/mapping/{userId}")
public String mappingPath(@PathVariable String userId) {
    log.info("mappingPath userId={}", userId);
    return "ok";
}
  • 위 코드와 비교해 보았을 때, 파라미터로 받은 userId와 변수명인 userId가 같으므로 코드를 이렇게 축약해서 쓸 수 있다.

-> @PathVariable(“userId”) String userId
-> @PathVariable String userId

둘은 같다.

✨ HTTP 요청 파라미터 - @RequestParam

@ResponseBody + @Controller => @RestController

파라미터 생략

생략 전

@ResponseBody
@RequestMapping("/request-param-v2")
public String requestParamV2(@RequestParam("username") String memberName,
                                @RequestParam("age") int memberAge) {
    log.info("username = {}, age = {}", memberName, memberAge);
    return "ok";
}

생략 후

@ResponseBody
@RequestMapping("/request-param-v3")
public String requestParamV3(@RequestParam String username,
                                @RequestParam int age) {
    log.info("username = {}, age = {}", username, age);
    return "ok";
}

PathVariable처럼, 변수명이 같으면 생략이 가능하다.

심지어, 이름이 맞고, String, int, Integer 등의 단순 타입인 경우 @RequestParam조차 생략이 가능하다.

@ResponseBody
@RequestMapping("/request-param-v4")
public String requestParamV4(String username, int age) {
    log.info("username = {}, age = {}", username, age);
    return "ok";
}

✨ HTTP 요청 파라미터 - @ModelAttribute

@RequestParam String username;
@RequestParam int age;

HelloData data = new HelloData();
data.setUsername(username);
data.setAge(age);

이렇게 값을 바인딩 해주는 부분을 @ModelAttribute를 통해 자동화시킬 수 있다.

@ResponseBody
@RequestMapping("/model-attribute-v1")
public String modelAttributeV1(@ModelAttribute HelloData helloData) {
    log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
    return "ok";
}

심지어 @ModelAttribute 또한 생략이 가능하다.

생략 시 int, String과 같은 단순 타입은 @RequestParam으로, 그 외는 @ModelAttribute로 해석한다.

✨ HTTP 요청 메시지 - 단순 텍스트

@RequestBody

  • @RequestBody 사용 시 HTTP 메시지 바디 정보를 편리하게 조회할 수 있다.
  • 헤더 정보 조회 시 HttpEntity 또는 @RequestHeader을 사용한다.

주의해야 할 점은, 만약 @RequestBody에 객체를 넣은 경우, 생략이 불가능하다는 점이다. 생략 시 @ModelAttribute가 붙어버리기 때문이다.

@RequestBody vs @ModelAttribute

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

정리

  • @PathVariable : url에서 정보를 가져올 때
  • @RequestParam : 아이디, 비밀번호와 같은 정보를 하나씩 가져올 때
  • @ModelAttribute : 아이디, 비밀번호와 같은 정보를 DTO와 같은 객체로 한 번에 전달 받을 때 + “사진” 과 같은 텍스트가 아닌 파일도 포함 or 그러한 파일인 경우
  • @RequestBody : 아이디, 비밀번호와 같은 정보를 DTO와 같은 객체로 한 번에 전달 받을 때 + json으로 전달 받을 때

대부분은 @RequestBody를 쓰되, 메시지 뿐 아니라 사진 등을 함께 전달 받아야 하는 경우에는 @ModelAttribute를 사용해 DTO로 데이터를 받는다.

카테고리:

업데이트: