Spring MVC Request처리 방법

선종우·2023년 5월 10일
0

1. 공부배경

사이드 프로젝트 중 스프링의 리퀘스트 처리 방법 관련 헷갈릴 때가 있어 정리하였다.

2. 공부내용

스프링 MVC에서는 총 5가지 방법을 이용해 HTTP Request를 처리할 수 있다. 5가지 방법은 아래와 같다.
a. HttpServletRequest 이용
b. @RequestParam 이용
c. @PathVariable 이용
d. @ModelAttribute 이용
e. @RequestBody 이용


a. HttpServletRequest 이용하는 방법

  • 설명 : JAVA EE가 제공하는 Servelet 기술을 이용하는 방법이다. 쿼리 스트링, 폼 데이터, MutipartFile 모두에 적용 가능하다.
  • 관련 공식 문서 : https://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html
  • 사용 예시
    public void getArticle(HttpServleRequest request){
    	//getParameter(파리미터명), 반환값은 String
    	String paramId = reqeust.getParameter("id");
      	// 반환값이 String이므로 다른 자료형을 사용한다면 변환 필요
      	Long id = Long.parseLong(paramId);
        //서비스 호출 로직
      	articeService.getArticle(id);
    }

b. @RequestParam

//별도 설정 없이 사용, 파라미터명(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);
}

c. @PathVariable

//별도 설정이 없는 경우 {}안의 값과 메소드 파라미터 이름을 연결시킨다.
@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);
}

d. @ModelAttribute

@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);
}

e.@RequestBody

@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);
}

3. 정리

  1. GET, POST, DELTE, PUT 메소드를 이용하며 1개 String, Int 등 단순한 값을 전달받을 때 : @ReqeustParam 이용

  2. REST API를 이용하며 특정 자원에 접근할 때 : @PathVariable

  3. POST, PUT메소드를 이용하며, Dto객체에 값을 편리하게 저장하고 싶을 때 : @ModelAttribute(생략 가능), Dto에는 생성자나 Setter선언

  4. POST, PUT메소드를 이용하며, JSON/XML과 같이 별도 파싱이 필요한 RequestBody를 Dto객체에 편리하게 저장하고 싶을 때 : @RequestBody

0개의 댓글