// MyDate 클래스
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 year;
}
public void setMonth(int month){
this.year = year;
}
public int getDay(){
return year;
}
public void setDay(int day){
this.year = year;
}
}
// 우클릭 -> generate -> getter and setter
@Controller
poublic class YoilTeller{
@RequestMapping("/getYoil")
public String main(Mydate myDate, Model model) throws IOException{
//2. 작업 - 요일을 계산
Calendar cal = Calendar.getInstance(); // 현재 날짜와 시간을 갖는 cal
cal.clear(); // cal의 모든 필드를 초기화
cal.set(myDate.getYear(), myDate.getMonth()-1, myDate.getDay()); // 월(mm)은 0~11이기 때문에 1을 빼줘야 함.
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); //1~7을 반환. 1:일요일, 2:월요일
char yoil = "일월화수목금토".charAt(dayOfWeek-1); 1~7 -> 0~6
//여기까지를 우클릭 -> Refactor -> Extract Method
private char getYoil(Mydate myDate){
Calendar cal = Calendar.getInstance(); // 현재 날짜와 시간을 갖는 cal
cal.clear(); // cal의 모든 필드를 초기화
cal.set(myDate.getYear(), myDate.getMonth()-1, myDate.getDay());
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
char yoil = "일월화수목금토".charAt(dayOfWeek-1); 1~7 -> 0~6
return yoil;
}
//그리고 작업은 다음과 같이 바뀜
char yoil = getYoil(myDate);
model.addAttribute("year", myDate.getYear());
model.addAttribute("month", myDate.getMonth());
model.addAttribute("day", myDate.getDay());
model.addAttribute("yoil");
1) WebDataBinder
@RequestMapping("/getYoilMVC5")
public String main(@ModelAttribute MyDate date, BindingResult result){
http://localhost/getYoilMVC5?year=2023&month=1&day=2
2) ModelAttribute
- 적용 대상을 Model의 속성으로 자동 추가해주는 annotation
- 반환 타입 또는 컨트롤러 메서드의 매개변수에 적용 가능