1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Java・JSP】includeディレクティブ (パーツの共通化)

Posted at

includeディレクティブ

「 パーツを共通化して使い回すための仕組み 」

【説明】

includeディレクティブは、このディレクティブを記述した位置に他のHTMLファイルやJSPファイルなどのテキストファイルを読み込みます。

【使用場面】

全JSPファイルで記述している内容を切り出し、共通化したい時に使用する。

WordPressでもヘッダー、フッター、サイドバーなどを共通化して使いまわしていましたがおそらくあのイメージかなと思います。

【基本構文】

以下がincludeディレクティブの構文です。

<%@ include file="(読み込みたいJSPファイルのパス)" %>

【使用方法】

読み込まれるファイル

こちらはヘッダーやフッターなどの共通化したいファイルを記述します。今回はHello Worldを出力する「hello.jsp」を用意して、他のjspファイルの任意の場所に出力します。

【hello.jsp】

<!-- 読み込み用ファイル -->
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<h1>Hello World</h1>

【include.jsp】

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>↓↓↓↓↓↓↓ここにinclude↓↓↓↓↓↓↓↓</h1>

	<!-- includeするjspファイルを指定する -->
	<%@ include file="header.jsp"%>

	<h1>↑↑↑↑↑↑↑ここにinclude↑↑↑↑↑↑↑↑</h1>
</body>
</html>

【出力結果(ブラウザ)】

↓↓↓↓↓↓↓ここにinclude↓↓↓↓↓↓↓↓

Hello World

↑↑↑↑↑↑↑ここにinclude↑↑↑↑↑↑↑↑

【まとめ】

これにより複数のページが必要なサイトやアプリでもパーツを共通化することでメンテナンスが非常に簡単になります。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?