15.JSP2.1 その他の追加機能
JSP2.1 第5章 その他の追加機能
JSP2.1にはUnified EL以外にも便利になった新機能があります。
5.1. @Resourceによるリソースインジェクション
Servlet2.5と同様、@Resourceアノテーションによるリソースインジェクションが行えるようになりました。 JSPではタグハンドラなどでの使用が考えられます。
@Resource(name="jdbc/myDB")
javax.sql.DataSource myDB;
public getProductsByCategory() {
// Get a connection and execute the query.
Connection conn = mydb.getConnection();
...
}
5.2 trimDirectiveWhitespaces属性
JSPのページディレクティブに追加されたtrimDirectiveWhitespaces属性をtrueにすることで、 生成されるHTMLから余分な空白行や余白を取り除き、 すっきりとした読みやすいHTMLコードを生成します。
たとえば以下のようなJSPを作成したとします。
<%@page contentType="text/html"%>
<%@page trimDirectiveWhitespaces="false"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<jsp:useBean id="conference" class="conf.Conference" scope="page" />
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test trimWhiteSpace directive</title>
</head>
<body>
<h1>Test trimWhiteSpace directive</h1>
Hello Pedro!<br>For the conference, you'll need to bring:<br>
<c:forEach items="${conference.items}" var="conf" varStatus="stat">
${conf} <br>
</c:forEach>
</body>
</html>
この場合、JSP2.1以前では以下のように余分な空白行やスペースがHTMLに出力されていました。 (¬ は空白行の終端位置を表しています。)
¬
¬
¬
¬
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test trimWhiteSpace directive</title>
</head>
<body>
<h1>Test trimWhiteSpace directive</h1>
¬
Hello Pedro!<br>For the conference, you'll need to bring:<br>
¬
laptop <br>
¬
white papers <br>
¬
candy bars <br>
¬
</body>
</html>
今回追加されたtrimDirectiveWhitespaces属性をtrueにすると、
<%@page trimDirectiveWhitespaces="true"%>
先ほどのページの空白行や余白が取り除かれ、以下のようにすっきりしたHTMLになりました。
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Test trimWhiteSpace directive</title> </head> <body> <h1>Test trimWhiteSpace directive</h1> Hello Pedro!<br>For the conference, you'll need to bring:<br> laptop<br> white papers<br> candy bars<br> </body> </html>

