Burninghering's Blog
article thumbnail

실습 결과 화면 1

유효하지 않을 시 결과 화면

실습 결과 화면 2

@ModelAttribute

적용 대상을 Model의 속성으로 자동 추가해주는 어노테이션 (Model에 자동 저장 -> 호출/저장 필요없음)

반환 타입 또는 컨트롤러 메서드의 매개변수에 적용 가능 

 

Model에 

Key와 value가 있다면,

"myDate"와 'data주소'가 저장된다.

컨트롤러 메소드 앞에 붙이기

호출 결과를 Model에 저장한다.

key와 value가 있다면

"yoil"과 '수'로 저장된다. 


코드가 간결해졌다!

package com.fastcampus.ch2;

import java.util.Calendar;

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

@Controller
public class YoilTellerMVC5 {
	
	@ExceptionHandler(Exception.class)
	public String catcher(Exception e) {
		return "yoilError";
	}
	
    @RequestMapping("/getYoilMVC5") // http://localhost/ch2/getYoilMVC5
//    public String main(@ModelAttribute("MyDate") MyDate date, Model model) { 아래와 동일
    public String main(@ModelAttribute MyDate date, Model model) { 
 
        // 1. 유효성 검사
    	if(!isValid(date)) 
    		return "yoilError";  // 유효하지 않으면, /WEB-INF/views/yoilError.jsp로 이동
    	
        // 2. 처리
//    	char yoil = getYoil(date);

        // 3. Model에 작업 결과 저장
//        model.addAttribute("myDate", date); //작업한 결과를 모델에 줄 때 key를 myDate로, value는 date로 
//        model.addAttribute("yoil", yoil);

        
        // 4. 작업 결과를 보여줄 View의 이름을 반환
        return "yoil"; // /WEB-INF/views/yoil.jsp
    }
    
    private boolean isValid(MyDate date) {
    	return isValid(date.getYear(),date.getMonth(),date.getDay());
	}

	private @ModelAttribute("yoil") char getYoil(MyDate date) {
    	return getYoil(date.getYear(),date.getMonth(),date.getDay());
	}

	private char getYoil(int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        cal.set(year, month - 1, day);

        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        return " 일월화수목금토".charAt(dayOfWeek);
    }
    
    private boolean isValid(int year, int month, int day) {    
    	if(year==-1 || month==-1 || day==-1) 
    		return false;
    	
    	return (1<=month && month<=12) && (1<=day && day<=31); // 간단히 체크 
    }
}

 

사실 @ModelAttribute가 생략 가능!

 

 

컨트롤러 매개변수의 

  • 타입이 기본형, String일 때는 RequestParam이 생략된 것으로 보면 된다.
  • 타입이 참조형일 때는 ModelAttribute이 생략된 것으로 보면 된다.

WebDataBinder

브라우저를 통해 요청 받은 값이 (year,month,day)

MyData 객체에 바인딩 될 때 중간 역할을 해준다. 

 

WebDataBinder가 하는 일 : 

1. 타입 변환 -> 결과/에러를 BindingResult에 저장 

2. 데이터 검증 -> 결과/에러를 BindingResult에 저장 

3. 컨트롤러에 넘겨줌 (컨트롤러가 결과 확인 가능)

 

@Controller
public class YoilTellerMVC6 {
	
	@ExceptionHandler(Exception.class)
	public String catcher(Exception ex, BindingResult result) { //컨트롤러까지 에러가 닿지도 못해서 여기서 에러 출력해보기
		System.out.println("result="+result);
		System.out.println("error="+result.getFieldError());
		
		FieldError error = result.getFieldError();
		
		System.out.println("code="+error.getCode());
		System.out.println("field="+error.getField());
		System.out.println("msg="+error.getDefaultMessage());
		
		return "yoilError";
	}
	
    @RequestMapping("/getYoilMVC6") // http://localhost/ch2/getYoilMVC6
//    public String main(@ModelAttribute("myDate") MyDate date, Model model) {
    public String main(MyDate date, BindingResult result) {
System.out.println("result="+result);
    	// 1. 유효성 검사
    	if(!isValid(date)) 
    		  return "yoilError";  // 유효하지 않으면, /WEB-INF/views/yoilError.jsp로 이동
    	
        // 2. 처리
//    	char yoil = getYoil(date);

        // 3. Model에 작업 결과 저장
//        model.addAttribute("myDate", date);
//        model.addAttribute("yoil", yoil);
        
        // 4. 작업 결과를 보여줄 View의 이름을 반환
        return "yoil"; // /WEB-INF/views/yoil.jsp
    }
    
    
    private @ModelAttribute("yoil") char getYoil(MyDate date) {
		    return getYoil(date.getYear(), date.getMonth(), date.getDay());
	  }

	  private char getYoil(int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        cal.set(year, month - 1, day);

        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        return " 일월화수목금토".charAt(dayOfWeek);
    }
    
    private boolean isValid(MyDate date) {    
    	if(date.getYear()==-1 || date.getMonth()==-1 || date.getDay()==-1) 
    		return false;
    	
    	return (1<=date.getMonth() && date.getMonth()<=12) && (1<=date.getDay() && date.getDay()<=31); // 간단히 체크 
    }
}

본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.

http://bit.ly/3Y34pE0

 

패스트캠퍼스 [직장인 실무교육]

프로그래밍, 영상편집, UX/UI, 마케팅, 데이터 분석, 엑셀강의, The RED, 국비지원, 기업교육, 서비스 제공.

fastcampus.co.kr

 

profile

Burninghering's Blog

@개발자 김혜린

안녕하세요! 반갑습니다.