사이드 프로젝트 중 스프링의 리퀘스트 처리 방법 관련 헷갈릴 때가 있어 정리하였다.
스프링 MVC에서는 총 5가지 방법을 이용해 HTTP Request를 처리할 수 있다. 5가지 방법은 아래와 같다.
a. HttpServletRequest 이용
b. @RequestParam 이용
c. @PathVariable 이용
d. @ModelAttribute 이용
e. @RequestBody 이용
public void getArticle(HttpServleRequest request){
//getParameter(파리미터명), 반환값은 String
String paramId = reqeust.getParameter("id");
// 반환값이 String이므로 다른 자료형을 사용한다면 변환 필요
Long id = Long.parseLong(paramId);
//서비스 호출 로직
articeService.getArticle(id);
}
//별도 설정 없이 사용, 파라미터명(id)을 이용해 값을 찾는다.
public void getArticle(@RequestParam Long id){
//서비스 호출 로직
articleService.getArticle(id);
}
//값이 존재하지 않을 수 있을 때는 required = false와 defaultValue = "값"을 지정해준다.
//required = false인데 값을 defaultValue를 지정하지 않은 경우 값이 없으면 null로 설정한다.
//이때 만약 파라미터를 primitive로 선언했다면 null을 할당할 수 없어 오류가 발생한다.
public void getArticle(@RequestParam(required false,
defaultValue = "name" String name,
@RequestParam Long id){
//서비스 호출 로직
articleService.getArticle(name, id);
}
//@ReqeustParam은 생략 가능하며 String, Int등 간단한 파라미터의 경우 @RequestParam(required = false)이 생략됐다고 간주하고 처리한다.
public void getArticle(Long id){
//서비스 호출 로직
articleService.getArticle(id);
}
//별도 설정이 없는 경우 {}안의 값과 메소드 파라미터 이름을 연결시킨다.
@GetMapping("/articles/{id}")
public void getArticle(@PathVariable Long id){
//서비스 호출 로직
articleService.getArticle(id);
}
//name 속성을 통해 {}안의 값과 메소드 파라미터를 직접 연결할 수 있다.
@GetMapping("/articles/{article_id}")
public void getArticle(@PathVariable(name = "article_id") Long id){
//서비스 호출 로직
articleServie.getArticle(id);
}
@Setter //lombok
public class ArticleDto{
private Long id;
private String title;
private String content;
}
---
@PostMapping("/articles/form")
public class createArticle(@ModelAttribute ArticleDto articleDto){
//서비스 로직
articleService.createArticle(articleDto);
// * 이때 model에는 articleDto라는 이름의 객체가 자동으로 등록되며, 이를 view에서 활용할 수 있다.
}
//@ModelAttribute를 생략가능하며, 객체 형태의 파라미터는 @ModelAttribute가 생략된 것으로 간주한다.
@PostMapping("/articles/form")
public class createArticle(ArticleDto articleDto){
//서비스 로직
articleService.createArticle(articleDto);
}
MessageConverter
전달되어 파싱된다.@Setter //lombok
public class ArticleDto{
private Long id;
private String title;
private String content;
}
---
@PutMapping("/articles/{id}")
public class updateArticle(@RequestBody ArticleDto articleDto){
//서비스 로직
articleService.updateArticle(articleDto);
}
GET, POST, DELTE, PUT 메소드를 이용하며 1개 String, Int 등 단순한 값을 전달받을 때 : @ReqeustParam
이용
REST API를 이용하며 특정 자원에 접근할 때 : @PathVariable
POST, PUT메소드를 이용하며, Dto객체에 값을 편리하게 저장하고 싶을 때 : @ModelAttribute(생략 가능)
, Dto에는 생성자나 Setter선언
POST, PUT메소드를 이용하며, JSON/XML과 같이 별도 파싱이 필요한 RequestBody를 Dto객체에 편리하게 저장하고 싶을 때 : @RequestBody