SeouliteLab

[Java/자바] Spring @ModelAttribute: 메서드 파라미터와 모델 속성의 바인딩 본문

프로그래밍

[Java/자바] Spring @ModelAttribute: 메서드 파라미터와 모델 속성의 바인딩

Seoulite Lab 2024. 3. 12. 11:21

Spring 프레임워크에서 @ModelAttribute 어노테이션은 HTTP 요청을 처리하는 컨트롤러의 메서드에서 모델 객체를 바인딩할 때 사용됩니다. 이 어노테이션은 주로 HTML 폼 데이터를 처리하고 뷰에 데이터를 전달하는 데 사용됩니다. 이 글에서는 @ModelAttribute 어노테이션의 사용법과 예제 코드를 통해 자세히 알아보겠습니다.

1. 기본적인 @ModelAttribute 사용법

가장 간단한 형태의 @ModelAttribute 어노테이션은 컨트롤러 메서드의 파라미터에 적용됩니다. 이 경우에는 해당 메서드가 호출되기 전에 모델 객체가 생성되어 바인딩됩니다.

예제 1: 기본적인 @ModelAttribute 사용법

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class MyController {

    @PostMapping("/submitForm")
    public String submitForm(@ModelAttribute("user") User user) {
        // 폼 데이터 처리 로직
        return "result";
    }
}

위의 예제에서는 /submitForm 경로로의 POST 요청을 처리하는 메서드입니다. 이 메서드는 User 클래스로 정의된 모델 객체를 user라는 이름으로 바인딩합니다.

2. 모델 객체 초기화

때로는 컨트롤러 메서드에 바인딩되는 모델 객체를 미리 초기화해야 할 때가 있습니다. @ModelAttribute 어노테이션은 이를 위해 초기화 메서드에 적용할 수도 있습니다.

예제 2: 초기화 메서드에 @ModelAttribute 사용하기

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class MyController {

    @ModelAttribute("user")
    public User getUserObject() {
        return new User();
    }

    @PostMapping("/submitForm")
    public String submitForm(@ModelAttribute("user") User user) {
        // 폼 데이터 처리 로직
        return "result";
    }
}

위의 예제에서는 getUserObject() 메서드가 호출되어 컨트롤러 메서드에서 사용할 모델 객체를 초기화합니다.

3. 예제 코드

다음은 @ModelAttribute 어노테이션을 사용한 예제 코드입니다.

예제 1: 기본적인 @ModelAttribute 사용법

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class MyController {

    @PostMapping("/submitForm")
    public String submitForm(@ModelAttribute("user") User user) {
        // 폼 데이터 처리 로직
        return "result";
    }
}

예제 2: 초기화 메서드에 @ModelAttribute 사용하기

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class MyController {

    @ModelAttribute("user")
    public User getUserObject() {
        return new User();
    }

    @PostMapping("/submitForm")
    public String submitForm(@ModelAttribute("user") User user) {
        // 폼 데이터 처리 로직
        return "result";
    }
}

4. 결론

이상으로 Spring의 @ModelAttribute 어노테이션에 대한 자세한 설명과 예제 코드를 살펴보았습니다. @ModelAttribute 어노테이션을 사용하여 컨트롤러 메서드에서 모델 객체를 효과적으로 바인딩할 수 있습니다.