Notice
Recent Posts
Recent Comments
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

충분히 쌓여가는

매개변수 묶어서 사용(@ModelAtrribute) 본문

Spring/연습

매개변수 묶어서 사용(@ModelAtrribute)

빌드이너프 2023. 10. 2. 17:36

YoilTeller(기존 코드)

매개변수가 int year, int month, int day로 되어 있다

package com.buildenough.ch2;

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

@Controller
public class YoilTeller {
    @RequestMapping("/getYoil")
    public String main(int year, int month, int day, Model model) throws IOException {

        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(year, month-1, day);

        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        char yoil = "일월화수목금토".charAt(dayOfWeek - 1);

        model.addAttribute("year", year);
        model.addAttribute("month", month);
        model.addAttribute("day", day);
        model.addAttribute("yoil", yoil);

        return "yoil";
    }
}

 

Mydate라는 클래스 생성 후 getter setter 추가

package com.buildenough.ch2;

public class Mydate {
    private int year;
    private int month;
    private int day;

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }
}

YoilTeller(변경 후 코드)

package com.buildenough.ch2;

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

@Controller
public class YoilTeller {
    @RequestMapping("/getYoil")
    public String main(Mydate mydate, Model model) throws IOException {

        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(mydate.getYear(), mydate.getMonth()-1, mydate.getDay());

        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        char yoil = "일월화수목금토".charAt(dayOfWeek - 1);

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

        return "yoil";
    }
}

요일 계산하는 부분 메서드로 만들기

Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(mydate.getYear(), mydate.getMonth()-1, mydate.getDay());

int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
char yoil = "일월화수목금토".charAt(dayOfWeek - 1);

 

Refactor -> Extract Method

package com.buildenough.ch2;

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

@Controller
public class YoilTeller {
    @RequestMapping("/getYoil")
    public String main(Mydate mydate, Model model) throws IOException {

        char yoil = getYoil(mydate);

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

        return "yoil";
    }

    private char getYoil(Mydate mydate) {
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(mydate.getYear(), mydate.getMonth()-1, mydate.getDay());

        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        char yoil = "일월화수목금토".charAt(dayOfWeek - 1);
        return yoil;
    }
}

Model에 저장하는 부분(DispatcherServlet이 Model을 View로 전달) 간단하게 하기 위해 @ModelAtrribute 사용

Mydate가 자동으로 Model에 저장됨

@ModelAttribute는 @RequestMapping으로 연결된 메서드의 매개변수 앞에 붙일 수 있고, 이때 매개변수는 참조형만 가능하다

그리고 메서드 앞에 붙이면 자동으로 메서드가 호출돼서 Model에 추가된다

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

 

@ModelAtrribute에 이름을 안주는 경우

package com.buildenough.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.io.IOException;
import java.util.Calendar;

@Controller
public class YoilTeller {
    @RequestMapping("/getYoil")
    public String main(@ModelAttribute("myDate") Mydate myDate, Model model) throws IOException {

        char yoil = getYoil(myDate);

        model.addAttribute("mydate", myDate);
        model.addAttribute("yoil", yoil);

        return "yoil";
    }

    private char getYoil(Mydate mydate) {
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(mydate.getYear(), mydate.getMonth()-1, mydate.getDay());

        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        char yoil = "일월화수목금토".charAt(dayOfWeek - 1);
        return yoil;
    }
}

 

안주면 타입의 첫글자를 소문자로 하기 때문에 model.addAttribute("myDate", myDate); 생략, @ModelAttribute 뒤에 "myDate" 생략

package com.buildenough.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.io.IOException;
import java.util.Calendar;

@Controller
public class YoilTeller {
    @RequestMapping("/getYoil")
    public String main(@ModelAttribute Mydate myDate, Model model) throws IOException {

        char yoil = getYoil(myDate);

        model.addAttribute("yoil", yoil);

        return "yoil";
    }


    private char getYoil(Mydate mydate) {
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(mydate.getYear(), mydate.getMonth()-1, mydate.getDay());

        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        char yoil = "일월화수목금토".charAt(dayOfWeek - 1);
        return yoil;
    }
}

 

이때 html 파일도 myDate를 붙여줘야한다

myDate.year, myDate.month, myDate.day

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>YoilTeller</title>
</head>
<body>
    <h1 th:text="|${myDate.year}년 ${myDate.month}월 ${myDate.day}일은 ${yoil}요일 입니다|"></h1>
</body>
</html>

model.addAttribute("yoil", yoil) 요일을 출력하는 부분 없애려면 getYoil 메서드 만든부분에 @ModelAttribute 붙인다

메서드 앞에 @ModelAttribute을 붙이면 메서드의 반환 타입이 여기에서는 "yoil"이라는 것으로 저장된다

package com.buildenough.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.io.IOException;
import java.util.Calendar;

@Controller
public class YoilTeller {
    @RequestMapping("/getYoil")
    public String main(@ModelAttribute Mydate myDate, Model model) throws IOException {

        char yoil = getYoil(myDate);
        
        return "yoil";
    }

    @ModelAttribute("yoil")
    private char getYoil(Mydate mydate) {
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(mydate.getYear(), mydate.getMonth()-1, mydate.getDay());

        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        char yoil = "일월화수목금토".charAt(dayOfWeek - 1);
        return yoil;
    }
}