[Spring] 스프링 MVC(7) - 커맨드 객체와 @ModelAttribute 어노테이션
커맨드 객체를 이용한 HTTP 요청
다음과 같이 HTTP 요청 파라미터가 많을 경우 일일이 @RequestParam 어노테이션을 사용해 코드를 작성한다면 매우 번거로울 것이다.
@RequestMapping(method = RequestMethod.POST)
public String regist(@RequestParam("email") String email,
@RequestParam("email") String name,
@RequestParam("password") String password,
@RequestParam("confirmPassword") String confirmPassword) {
// 이하 생략
...
return "member/registered";
}
이럴 경우 일일이 파라미터를 추가하는 것보다는 다음과 같이 요청 파라미터를 값으로 전달받을 객체를 메서드의 파라미터 지정해주면 된다.
@RequestMapping(method = RequestMethod.POST)
public String regist(MemberRegistRequest memRegReq) {
// 이하 생략
...
return "member/registered";
}
public class MemberRegistRequest {
private String email;
private String name;
private String password;
private String confirmPassword;
// 이하 getter, setter 생략
...
}
스프링 MVC는 @RequestMapping이 적용된 메서드의 파라미터에 객체를 추가하면, 그 객체의 set 메서드를 호출해서 요청 파라미터 값을 전달한다. 값을 전달할 때는 같은 이름을 갖는 요청 파라미터와 프로퍼티를 매핑한다.(예. memRegReq.setEmail() -> email)
여기서 MemberRegistRequest 객체와 같이 HTTP 요청 파라미터 값을 전달받을 때 사용되는 객체를 커맨드 객체라고 부른다.
@ModelAttribute를 이용한 커맨드 객체 이름 지정
커맨드 객체는 첫 글자를 소문자로 바꾼 클래스 이름을 이용해서 모델에서 접근할 수 있다. 이때 클래스 이름이 다소 길어서 다른 이름을 대신 사용하고 싶다면 다음과 같이 @ModelAttribute 어노테이션을 사용하면 된다.
@Controller
@RequestMapping("/member/regist")
public class RegistrationController {
@RequestMapping(method = RequestMethod.POST)
public String regist(@ModelAttribute("memberInfo") MemberRegistRequest memRegReq) {
// 이하 생략
...
return "member/registered";
}
// 이하 생략
...
}
@ModelAttribute를 이용한 공통 모델 처리
다음과 같이 @ModelAttribute 어노테이션을 메서드에 사용하면, 코드를 중복하지 않으면서 함께 사용되는 데이터를 설정할 수 있다.
@Controller
@RequestMapping("/event")
public class EventController {
@ModelAttribute("recEventList")
public List<Event> recommend() {
return eventService.getRecommendedEventService();
}
// 이하 생략
...
}
위 코드에서 recommend() 메서드에 @ModelAttribute 어노테이션을 붙였는데, 스프링 MVC는 recommend() 메서드의 리턴 결과를 "recEventList" 모델 속성으로 추가한다. 따라서 요청 경로에 상관없이 뷰 코드에서는 "recEventList" 이름을 이용해서 recommend() 메서드가 리턴한 객체 접근할 수 있다.
@ModelAttribute 어노테이션이 적용된 메서드의 객체를 @RequestMapping 어노테이션이 적용된 메서드에서 접근할 수도 있다. 다음과 같이 같은 값을 갖는 @ModelAttribute 어노테이션을 사용하면 된다.
@ModelAttribute("recEventList")
public List<Event> recommend() {
return eventService.getRecommendedEventService();
}
@RequestMapping("/list")
public String list(@ModelAttribute("recEventList") List<Event> recEventList, Model model) {
// 이하 생략
...
}
위 코드에서 list() 메서드의 첫 번째 파라미터로 전달되는 객체는 recommend() 메서드가 리턴한 객체가 된다.
Reference
- 웹 개발자를 위한 Spring 4.0 프로그래밍 (최범균 저)