LoginSignup
18
22

More than 5 years have passed since last update.

JSPでレイアウトのテンプレートを作る

Posted at

●基本

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

このようにコード内にインポートするjspファイルを書くとそのページを読み込むことができる。

【全体のコード例】

<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
<head>
<title>test\</title>
</head>
<body>
<jsp:include page="header.jsp"/>
<div id="main">
contents
</div>
<jsp:include page="footer.jsp"/>
</body>
</html>

この例ではヘッダーとフッターをそれぞれjspファイルを読み込んでいるので、header.jspやfotter.jspを変えるとこのページのレイアウトも変わる

●外枠を作りたい場合

レイアウトの中に${param.title}というように param.パラメータ名 でテンプレート読込先の内容を変えることができる

取り出しはテンプレート読込先で

<jsp:param name="title" value="テスト"/>
または
<jsp:param name="content">
<jsp:attribute name="value">
test //ここにcontentの中身がくる
</jsp:attribute>
</jsp:param>

のように書くと中身をテンプレートに入れ込むことができる


・main_layout.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
<head>
<title>${param.title}</title>
</head>
<body>
<jsp:include page="header.jsp"/>
<jsp:include page="navigation.jsp"/>
<div id="main">
${param.content}
</div>
<jsp:include page="footer.jsp"/>
</body>
</html>

・sample.jsp

<%@page pageEncoding="UTF-8" contentType="text/html" %>
<jsp:include page="../layout/main_layout.jsp">
<jsp:param name="title" value="テスト">
<jsp:param name="content">
<jsp:attribute name="value">
test //ここにcontentの中身がくる
</jsp:attribute>
</jsp:param>
</jsp:include>

18
22
1

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
18
22