패스트캠퍼스 데브캠프 : 남궁성의 백엔드 개발 3기

Spring MVC | @ModelAttribute

Tech_JINI 2025. 2. 28. 12:26
더보기
package com.fastcampus.ch2;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Calendar;

@Controller

public class YoilController {

    @RequestMapping("/yoil")
    public String yoli(MyDate myDate, Model model){ //매개 변수가 너무 많아질 경우 MyDate타입으로 정의

        char yoil = getYoil(myDate);

        model.addAttribute("year", myDate.getYear());
        model.addAttribute("month", myDate.getMonth());
        model.addAttribute("day", myDate.getDay());
        model.addAttribute("yoil", yoil);

        return "yoilView";

    }

    private char getYoil(MyDate myDate) {
        // 요일을 계산
        Calendar cal = Calendar.getInstance(); //현재 날짜와 시간을 갖는 cal
        cal.clear(); // 초기화
        cal.set(myDate.getYear(), myDate.getMonth()-1, myDate.getDay()); //월은 0부터 11까지이기 때문에 1을 빼줘야함

        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); // 1~7변환, 1:일요일, 2:월요일
        char yoil = "일월화수목금토".charAt(dayOfWeek-1); // 1~7 -> 0~6
        return yoil;
    }

@ModelAttribute 를 통해 위의 코드를 더 단순화 시킬 수 있다.

 

이 코드에서 @ModelAttribute은 myDate 객체를 모델에 담겠다는 뜻이 된다. 따라서 아래코드를 생략할 수 있다.

//        model.addAttribute("year", myDate.getYear());
//        model.addAttribute("month", myDate.getMonth());
//        model.addAttribute("day", myDate.getDay());

  마치 위의 코드를 생략하고 model.addAttribute("myDate", myDate);를 한 것과 같은 의미이다. 

 

 

@ModelAttribute("이름")를 메서드 앞에 붙이게 되면 메서드의 반환 타입이 "이름"이라는 이름으로 저장이 된다. 

더보기

 

package com.fastcampus.ch2;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Calendar;

@Controller

public class YoilController {

    @RequestMapping("/yoil")
    public String yoli(@ModelAttribute MyDate myDate, Model model){ //매개 변수가 너무 많아질 경우 MyDate타입으로 정의

        char yoil = getYoil(myDate);

        return "yoilView"; //뷰의 이름을 반환

    }
    @ModelAttribute("yoil")
    private char getYoil(MyDate myDate) {
        // 요일을 계산
        Calendar cal = Calendar.getInstance(); //현재 날짜와 시간을 갖는 cal
        cal.clear(); // 초기화
        cal.set(myDate.getYear(), myDate.getMonth()-1, myDate.getDay()); //월은 0부터 11까지이기 때문에 1을 빼줘야함

        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); // 1~7변환, 1:일요일, 2:월요일
        char yoil = "일월화수목금토".charAt(dayOfWeek-1); // 1~7 -> 0~6
        return yoil;
    }
}

따라서

model.addAttribute("yoil", yoil);

를 생략할 수 있다. 

 

@ModelAttribute 의 사용법은 2가지이다.

- @RequestMapping으로 연결된 메서드에 참조형 매개변수 앞에 붙이면, 객체가 모델에 자동으로 저장된다. 

- 메서드 앞에 붙이면 @ModelAttribute가 붙은 메서드가 자동으로 호출되어 그 결과가 모델에 추가된다. 

 

@ModelAttribute가 붙어 있는 메서드는 여러 개를 호출할 수 있고, 컨트롤러 안에 있는 @ModelAttribute가 붙은 메서드들을 자동으로 호출하여 그 결과가 모델에 다 저장이 된다. 

 

더보기

@ModelAttribute 사용하지 않은 코드

package com.fastcampus.ch2;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;

@Controller

public class YoilController {

    @RequestMapping("/yoil")
    public String yoli(String year, String month, String day, Model model){
    public String yoli(MyDate myDate, Model model){ //매개 변수가 너무 많아질 경우 MyDate타입으로 정의

        System.out.println("year = " + year);
        System.out.println("month = " + month);
        System.out.println("day = " + day);

        model.addAttribute("year", year);
        model.addAttribute("month", month);
        model.addAttribute("day", day);
        char yoil = getYoil(myDate);

        return "yoilView";

        //데이터를 model에 저장 -> view로 전달받을 것임
        model.addAttribute("year", myDate.getYear());
        model.addAttribute("month", myDate.getMonth());
        model.addAttribute("day", myDate.getDay());
        model.addAttribute("yoil", yoil);

        return "yoilView"; //뷰의 이름을 반환

    }

    private char getYoil(MyDate myDate) {
        // 요일을 계산
        Calendar cal = Calendar.getInstance(); //현재 날짜와 시간을 갖는 cal
        cal.clear(); // 초기화
        cal.set(myDate.getYear(), myDate.getMonth()-1, myDate.getDay()); //월은 0부터 11까지이기 때문에 1을 빼줘야함

        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); // 1~7변환, 1:일요일, 2:월요일
        char yoil = "일월화수목금토".charAt(dayOfWeek-1); // 1~7 -> 0~6
        return yoil;
    }

 

더보기

@ModelAttribute 사용한 코드

package com.fastcampus.ch2;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;

@Controller

public class YoilController {

    @RequestMapping("/yoil")
    public String yoli(@ModelAttribute MyDate myDate, Model model){ //매개 변수가 너무 많아질 경우 MyDate타입으로 정의

        return "yoilView"; //뷰의 이름을 반환

    }
    @ModelAttribute("yoil")
    private char getYoil(MyDate myDate) {
        // 요일을 계산
        Calendar cal = Calendar.getInstance(); //현재 날짜와 시간을 갖는 cal
        cal.clear(); // 초기화
        cal.set(myDate.getYear(), myDate.getMonth()-1, myDate.getDay()); //월은 0부터 11까지이기 때문에 1을 빼줘야함

        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); // 1~7변환, 1:일요일, 2:월요일
        char yoil = "일월화수목금토".charAt(dayOfWeek-1); // 1~7 -> 0~6
        return yoil;
    }

}