[Spring Boot] Spring Boot @RequestParam 완벽 가이드: HTTP 요청 파라미터 처리하기
[Spring Boot] Spring Boot @RequestParam 완벽 가이드: HTTP 요청 파라미터 처리하기
[Spring Boot] Spring Boot Handler Method의 WebRequest 파라미터 사용법과 실무 예제 [Spring Boot] Spring Boot Handler Method의 WebRequest 파라미터 사용법과 실무 예제[Spring Boot] @RequestMapping Class Level 매핑 - Spring Boot Cont
crushed-taro.tistory.com
1. Handler Method
1. @ModelAttrribute
index.html에서 GET 방식의 /first/search요청을 전달한다.
<h3>3. @ModelAttribute를 이용하여 파라미터 전달 받기</h3>
<button onclick="location.href='/first/search'">@ModelAttribute 이용하기</button>
Controller 클래스의 핸들러 메소드를 통해 파라미터 전달 테스트를 위해 값을 입력할 수 있는 뷰를 응답한다.
@Controller
@RequestMapping("/first/*")
public class FirstController {
@GetMapping("search")
public void search() {}
...생략
}
resources/templates/first 의 하위에 search.html파일을 생성한다.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>search</title>
</head>
<body>
<h1>@ModelAttribute를 이용한 커맨드 객체로 파라미터 값 전달받기</h1>
<form action="search" method="post">
검색할 메뉴 이름 : <input type="text" name="name"><br>
검색할 메뉴 가격 : <input type="number" name="price"><br>
검색할 메뉴의 카테고리 :
<select name="categoryCode">
<option value="1">식사</option>
<option value="2">음료</option>
<option value="3">디저트</option>
</select><br>
검색할 판매 상태 : <input type="text" name="orderableStatus"><br>
<input type="submit" value="검색하기">
</form>
</body>
</html>
해당 화면에서 사용자 입력 양식에 값을 입력하고 submit 을 누르면 POST 방식의 /first/search요청이 발생한다.
DTO 같은 모델을 커맨드 객체로 전달 받는 테스트를 위해서 MenuDTO를 만든다.
DTO를 작성할 때 커맨드 객체로 이용하기 위해서는 form의 name값과 필드명을 일치하게 만들어야 한다.
또한 커맨드 객체는 기본생성자를 이용하여 인스턴스를 만들기 때문에 기본생성자가 반드시 필요하다.
요청 파라미터의 name과 일치하는 필드의 setter를 이용하기 때문에 네이밍 룰에 맞는 setter메소드가 작성되어야 한다.
public class MenuDTO {
private String name;
private int price;
private int categoryCode;
private String orderableStatus;
public MenuDTO() {}
public MenuDTO(String name, int price, int categoryCode, String orderableStatus) {
super();
this.name = name;
this.price = price;
this.categoryCode = categoryCode;
this.orderableStatus = orderableStatus;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getCategoryCode() {
return categoryCode;
}
public void setCategoryCode(int categoryCode) {
this.categoryCode = categoryCode;
}
public String getOrderableStatus() {
return orderableStatus;
}
public void setOrderableStatus(String orderableStatus) {
this.orderableStatus = orderableStatus;
}
@Override
public String toString() {
return "MenuDTO [name=" + name + ", price=" + price + ", categoryCode=" + categoryCode
+ ", orderableStatus=" + orderableStatus + "]";
}
}
발생하는 요청을 매핑할 controller의 handler method이다.
@ModelAttribute의 경우 커맨드 객체를 생성하여 매개변수로 전달해 준 뒤 해당 인스턴스를 model에 담는다.
화면에서 출력해보면 모델에 담겨진 값을 확인할 수 있다. 경우에 따라 폼에서 입력한 값을 다음 화면으로 바로 전달해야 하는 경우가 발생하는데 이 때 유용하게 사용할 수 있다.
@ModelAttribute("모델에담을key값")을 지정할 수 있으며, 지정하지 않으면 타입의 앞글자를 소문자로 한 네이밍 규칙을 따른다.
해당 어노테이션은 생략이 가능하지만 명시적으로 작성하는 것이 좋다.
@PostMapping("search")
public String searchMenu(@ModelAttribute("menu") MenuDTO menu) {
System.out.println(menu);
return "first/searchResult";
}
응답 화면을 구성하기 위해 resources/templates/first 의 하위에 searchResult.html파일을 생성한다.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>searchResult</title>
</head>
<body>
<h1>Model에 담긴 커맨드 객체의 정보 출력</h1>
<h3 th:text="|메뉴의 이름 : ${ menu.name }|"></h3>
<h3 th:text="|메뉴의 가격 : ${ menu.price }|"></h3>
<h3 th:text="|메뉴의 카테고리 : ${ menu.categoryCode }|"></h3>
<h3 th:text="|메뉴의 판매상태 : ${ menu.orderableStatus }|"></h3>
</body>
</html>
클라이언트에서 입력 된 값이 컨트롤러 핸들러 메서드의 MenuDTO타입의 객체에 잘 담겨서 전달 되었음을 응답 화면을 통해 확인할 수 있다.