1. 정적 포함 (<%@ include %> Directive)

정적 포함은 컴파일 시 포함할 JSP 파일의 내용을 컴파일 타임 포함된다. 이는 JSP가 변환될 때 포함된 파일의 내용이 대상 JSP에 합쳐져 하나의 서블릿으로 변환된다.

사용법:

<%@ include file="header.jsp" %>
 

특징:

  • 포함 파일 내용이 컴파일 시점에 병합됩니다.
  • 포함된 JSP 파일은 원본 JSP와 함께 하나의 서블릿 파일로 컴파일됩니다.
  • 주로 공통적인 HTML 구조(예: 헤더, 푸터, 사이드바)를 삽입할 때 유용합니다.
  • 파일의 변경 사항은 JSP를 다시 컴파일해야 반영됩니다.

예제:

header.jsp

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Website</title>
</head>
<body>
    <h1>Welcome to My Website</h1>
</body>
</html>

index.jsp

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Website</title>
</head>
<body>
    <%@ include file="header.jsp" %>
    <p>This is the main content.</p>
</body>
</html>

결과 출력:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Website</title>
</head>
<body>
    <h1>Welcome to My Website</h1>
    <p>This is the main content.</p>
</body>
</html>
 

2. 동적 포함 (<jsp:include /> Action Tag)

동적 포함은 런타임 시점에 다른 JSP 파일의 내용 포함함 이 방식은 요청 시 포함된 파일을 실행하고 결과를 현재 JSP에 포함

사용법:

<jsp:include page="footer.jsp" />

특징:

  • 포함된 파일은 독립적으로 컴파일되고 실행됩니다.
  • 포함 파일의 변경 사항이 즉시 반영됩니다.
  • 요청마다 결과를 동적으로 가져오므로 요청 시 실행 결과를 삽입합니다.
  • 주로 동적인 콘텐츠(예: 현재 날짜, 사용자 정보 등)를 삽입할 때 유용합니다.

예제:

footer.jsp

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Website</title>
</head>
<body>
    <h1>Welcome to My Website</h1>
    <p>This is the main content.</p>

    <footer>
        <p>&copy; 2024 My Website</p>
    </footer>
</body>
</html>
 

index.jsp

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Website</title>
</head>
<body>
    <h1>Welcome to My Website</h1>
    <p>This is the main content.</p>

    <jsp:include page="footer.jsp" />
</body>
</html>

결과 출력:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Website</title>
</head>
<body>
    <h1>Welcome to My Website</h1>
    <p>This is the main content.</p>

    <footer>
        <p>&copy; 2024 My Website</p>
    </footer>
</body>
</html>

정적 포함과 동적 포함의 차이점

특징정적 포함 (<%@ include %>)동적 포함 (<jsp:include />)

포함 시점 컴파일 타임 런타임
변경 반영 JSP 재컴파일 필요 즉시 반영
성능 한 번 컴파일된 후 빠름 요청마다 실행되므로 다소 느릴 수 있음
용도 공통적인 HTML 구조 삽입 동적인 콘텐츠 삽입

선택 기준

  • 정적 포함: 레이아웃 템플릿처럼 변경되지 않는 고정된 파일을 포함할 때.
  • 동적 포함: 변경될 가능성이 있는 동적인 파일이나 데이터를 삽입할 때.

'WEB' 카테고리의 다른 글

SQL Session Factory  (0) 2024.12.02
이미지 파일저장  (0) 2024.11.21
Scope  (0) 2024.11.20
서블릿 리스너  (0) 2024.11.20
서블릿 filter 설명  (0) 2024.11.20

+ Recent posts