Spring

11. 관심사의 분리와 MVC패턴/이론 - 패스트캠퍼스 백엔드 부트캠프 3기

gkss2tpt 2025. 2. 1. 16:02

1. OOP 5대 설계원칙 - SOLID

  • SRP(Single Responsibility Principle): 단일 책임 원칙
    • 하나의 메서드는 하나의 책임(관심사)만 진다.

2. 관심사의 분리 Separation of Concerns

  • 관심사(Concern) : 해야할 작업
  • 분리
    •  관심사의 분리
    • 변하는것(Common), (자주)변하지 않는것(Uncommon)의 분리
    • 중복 코드의 분리

3. 공통 코드의 분리 - 입력의 분리

@RequestMapping("/getYoil")
public void main(HttpServletRequest request,
		HttpServletResponse response) throws IOException {
    // 1. 입력
    String year = request.getParameter("year");
    String month = request.getParameter("month");
    String day = request.getParameter("day");
    
    int yyyy = Integer.parseInt(year);
    int mm = Integer.parseInt(month);
    int dd = Integer.parseInt(day);
}
  • 입력의 분리1
@RequestMapping("/getYoil")
public void main(String year, String month, String day,
		HttpServletResponse response) throws IOException {
    
    int yyyy = Integer.parseInt(year);
    int mm = Integer.parseInt(month);
    int dd = Integer.parseInt(day);
}
  • 입력의 분리2(자동변환)
@RequestMapping("/getYoil")
public void main(int year, int month, int day,
		HttpServletResponse response) throws IOException {
    
    // 2. 처리
    Calendar cal = Calendar.getInstance();
    cal.set(year, month - 1, day);
}
  • 출력의 분리 - 변하는 것과 변하지 않는 것의 분리
@RequestMapping("/getYoil")
public void main(int year, int month, int day,
		HttpServletResponse response) throws IOException {
    
	// 2. 처리 Controller
	Calendar cal = Calendar.getInstance();
	cal.set(yyyy, mm-1, dd);
		
	int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
	char yoil = " 일월화수목금토".charAt(dayOfWeek);
    
   	// Model 객체로 연결
		
	// 3. 출력 View
	response.setContentType("text/html");	// 응답의 형식을 html로 지정
	response.setCharacterEncoding("utf-8");	// 응답의 인코딩을 utf-8로 지정
	PrintWriter out = response.getWriter();	// 브라우저로의 출력 스트림(out)을 얻는다.
	out.println("<html>");
	out.println("<head>");
	out.println("</head>");
	out.println("<body>");
	out.println(year + "년 " + month + "월 " + day + "일은 ");
	out.println(yoil + "요일입니다.");
	out.println("</body>");
	out.println("</html>");
	}
}

 

4. MVC패턴

  • (2),(3)
@RequestMapping("/getYoil")
public String main(int year, int month, int day, Model model) {
     // 1. 유효성 검사
     if(!isValid(year, month, day))
         return "yoilError";	// 유효하지 않으면, /WEB-INF/views/yoilError.jsp 로 이동
         
     // 2. 처리
     char yoil = getYoil(year, month, day);
     
     // 3. Model에 작업 결과 저장
     model.addAttribute("year", year);
     model.addAttribute("month", month);
     model.addAttribute("day", day);
     model.addAttribute("yoil", yoil);
     
     // 4. 작업 결과를 보여줄 View의 이름을 반환
     return "yoil";	// /WEB-INF/views/yoil.jsp
}
  • (4)
[yoil.jsp]
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
    <title>YoilTellerMVC</title>
</head>
<body>
<h1>${year}년 ${month}월 ${day}일은 ${yoil}요일입니다.</h1>
</body>
</html>