Java/Spring Boot

[Java / Spring Boot] Model과 MVC 패턴

2025. 1. 14. 16:37

Model

컨트롤러와 뷰 사이의 데이터 전달을 담당하는 객체

@RequestMapping("/list")
public String list(Model model) {
    List<PokemonDto> list = pokemonDao.selectList();
    model.addAttribute("list", list);
    return "/WEB-INF/views/pokemon/list.jsp";
}

.addAttribute()

데이터를 `Model`객체에 추가하는 메서드

  • `key`와 `value`를 인자로 넘김
model.addAttribute("list", list);

JSP

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<jsp:include page="/WEB-INF/views/template/header.jsp"></jsp:include>

<h1>포켓몬 목록</h1>
<h2><a href="add">신규등록</a></h2>

<table border="1" width="400">
	<thead>
		<tr>
			<th>번호</th>
			<th>이름</th>
			<th>속성</th>
		</tr>
	</thead>
	<tbody align="center">
		<c:forEach var="pokemonDto" items="${list}">
		<tr>
			<td>${pokemonDto.pokemonNo}</td>
			<td>
				<a href="detail?pokemonNo=${pokemonDto.pokemonNo}">
					${pokemonDto.pokemonName}
				</a>
			</td>
			<td>${pokemonDto.pokemonType}</td>
		</tr>
		</c:forEach>
	</tbody>
</table>

<jsp:include page="/WEB-INF/views/template/footer.jsp"></jsp:include>

EL (Expression Language)

컨트롤러에서 전달된 데이터를 화면에 출력하기 위해 사용하는 언어

  • JSP에서 Java 코드를 직접 사용할 경우 발생하는 부작용을 상쇄
  • 추론 기능 제공 (`pokemonDto.getPokemonNo()` > `pokemonDto.pokemonNo`)
  • `${}` 안에서 사용
${pokemonDto.pokemonNo}

 

JSTL (JSP Standard Tag Library)

사용자가 보는 화면에서 조건, 반복 등 간단한 프로그래밍이 필요한 경우 사용

  • EL은 값을 지정해서 보여주는 것만 가능하므로 부족한 부분을 보충
  • 종류가 다양하지만 실제로 사용하는 것은 조건, 반복, 날짜 / 숫자 형식 정도
  • taglib directive를 선언하고 사용해야함

<c:forEach>

컬렉션, 배열, `Iterable` 객체를 반복하면서 각 항목에 대해 작업을 수행

  • `var` - 각 반복 항목에 접근할 때 사용할 변수 이름
  • `items` - 반복할 대상
<c:forEach var="item" items="${list}">
    <!-- 반복할 내용 -->
    <p>${item}</p>
</c:forEach>

 

<c:if>

조건문 처리하는데 사용

  • `test` - 조건을 나타내는 EL식
<c:if test="${condition}">
    <!-- 조건이 true일 때 실행할 내용 -->
</c:if>

 

<c:choose>

복수 조건문 처리하는데 사용

<c:choose>
    <c:when test="${condition1}">
        <!-- condition1이 true일 때 실행할 내용 -->
    </c:when>
    <c:when test="${condition2}">
        <!-- condition2가 true일 때 실행할 내용 -->
    </c:when>
    <c:otherwise>
        <!-- 모든 조건이 false일 때 실행할 내용 -->
    </c:otherwise>
</c:choose>

 

<c:when>

`<c:choose>`내에서 사용되는 조건문

<c:choose>
    <c:when test="${num == 1}">
        <p>Number is 1</p>
    </c:when>
    <c:when test="${num == 2}">
        <p>Number is 2</p>
    </c:when>
    <c:otherwise>
        <p>Number is not 1 or 2</p>
    </c:otherwise>
</c:choose>

 

<c:otherwise>

`<c:choose>` 조건문에서 모든 조건이 만족되지 않았을 때 기본적으로 실행

<c:choose>
    <c:when test="${num == 1}">
        <p>Number is 1</p>
    </c:when>
    <c:when test="${num == 2}">
        <p>Number is 2</p>
    </c:when>
    <c:otherwise>
        <p>Number is something else</p>
    </c:otherwise>
</c:choose>

 

<fmt:formatDate>

날짜를 지정된 형식에 맞게 출력

  • `value` - 형식을 적용할 날짜 객체
  • `pattern` - 날짜를 출력할 형식 (`SimpleDateFormat`의 형식 규칙을 따름)
<fmt:formatDate value="${date}" pattern="yyyy-MM-dd"/>

 

<fmt:formatNumber>

숫자를 지정된 형식에 맞게 출력

  • `value` - 형식을 적용할 숫자
  • `pattern` - 숫자를 출력할 형식 (`DecimalFormat`의 형식 규칙을 따름)
<fmt:formatNumber value="${price}" pattern="###,###.##"/>

MVC (Model View Controller) 패턴

처리 과정

  1. 사용자가 요청을 보냄
  2. 서블릿 컨테이너가 요청을 수신하여 중앙분배기로 전달
  3. 중앙분배기에서 `HandlerMapping`을 통해 주소에 매핑되는 컨트롤러를 찾음
  4. 모델에서 필요한 데이터를 찾음
  5. 찾은 데이터를 컨트롤러로 가져옴
  6. 매핑된 컨트롤러를 `HandlerAdapter`를 통해 호출
  7. `ViewResolver`를 통해 컨트롤러와 매핑되는 뷰를 찾음
  8. 찾은 뷰를 `ViewResolver`를 통해 중앙분배기로 가져옴
  9. 서블릿 컨테이너로 뷰를 전달
  10. 뷰를 사용자에게 응답

Servlet Container

Java 웹 애플리케이션을 실행하기 위한 서버 환경 (주로 Apache Tomcat이 내장되어 쓰임)

  • HTTP 요청 및 응답 처리
  • 서블릿 생명주기 관리
  • 멀티스레드 처리
  • URL 매핑
  • JSP 지원
  • 필터와 리스너 지원
  • 보안 관리
  • 애플리케이션 배포 및 실행

 

DispatcherServlet

클라이언트로부터 들어오는 모든 HTTP 요청을 가로채어 컨트롤러, 뷰로 전달하고 응답을 반환하는 역할

 

HandlerMapping

클라이언트의 요청 URL을 처리할 적절한 핸들러(`Controller` 메서드)를 찾아 반환

  • `@RequestMapping`, `@GetMapping`, `@PostMapping` 등

 

HandlerAdapter

찾아낸 핸들러(`Controller`)를 실제로 실행할 수 있도록 호출하는 역할

  • `@Controller`, `@RestController` 등

 

ViewResolver

컨트롤러가 반환한 뷰 이름을 실제로 렌더링할 뷰로 매핑하는 역할

  • `/WEB-INF/views/home.jsp` 등

 

'Java > Spring Boot' 카테고리의 다른 글

[Java / Spring Boot] AOP와 Interceptor, Configuration  (2) 2025.01.15
[Java / Spring Boot] Session  (0) 2025.01.15
[Java / Spring Boot] Forward와 Redirect  (0) 2025.01.14
[Java / Spring Boot] View (JSP)  (0) 2025.01.09
[Java / Spring Boot] Lombok과 JDBC 연결  (0) 2025.01.08
'Java/Spring Boot' 카테고리의 다른 글
  • [Java / Spring Boot] AOP와 Interceptor, Configuration
  • [Java / Spring Boot] Session
  • [Java / Spring Boot] Forward와 Redirect
  • [Java / Spring Boot] View (JSP)
개발하는 벌꿀오소리
개발하는 벌꿀오소리
겁없는 벌꿀오소리처럼 끊임없이 도전하자!
  • 글쓰기 관리
  • 개발하는 벌꿀오소리
    벌꿀오소리의 개발 노트
    개발하는 벌꿀오소리
  • 전체
    오늘
    어제
    • 분류 전체보기 (74)
      • Java (60)
        • 기본 (23)
        • 모듈 (8)
        • 자료구조 (5)
        • 알고리즘 (0)
        • 파일 입출력 (5)
        • JDBC (5)
        • Spring Boot (14)
      • Oracle (13)
      • Project (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 인기 글

  • 공지사항

  • hELLO· Designed By정상우.v4.10.3
개발하는 벌꿀오소리
[Java / Spring Boot] Model과 MVC 패턴
상단으로

티스토리툴바