カスタムタグライブラリを利世するコードを紹介します。
コード
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="/EasyCustomLibrary" prefix="easy" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Easy Custom Library</title>
</head>
<body>
<h1>Easy Custom Library</h1>
<br><hr><br>
<FONT size="20"><easy:EasyCustom /></FONT>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=
"http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<jsp-config>
<taglib>
<taglib-uri>/EasyCustomLibrary</taglib-uri>
<taglib-location>/WEB-INF/tlds/easycustom.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>
解説
taglibタグでカスタムタグライブラリのURIとtldファイルを指定します。
以前のバージョンではWeb-appタグ直下にtaglibタグを記述できましたが、
最近のバージョンはjsp-configタグ内にtaglibタグを記述します。
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation
="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd">
<tlib-version>1.2</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>Easy Tag Library</short-name>
<tag>
<name>EasyCustom</name>
<tag-class>webApplication19.EasyCustom</tag-class>
</tag>
<uri>/WEB-INF/tlds/easycustom</uri>
</taglib>
解説
tldファイルにはタグの名称、タグの処理をするクラス名を指定します。
package webApplication19;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
public class EasyCustom extends TagSupport {
private PageContext pc = null;
public void setPageContext(PageContext pc) {
this.pc = pc;
}
public int doStartTag() throws JspException {
//JSPに対する出力ストリームの取得
JspWriter out = pc.getOut();
try {
out.println("Hello Easy Custom World !!");
} catch (Exception e) {
throw new JspException(e);
}
//BODY処理をスキップ
return SKIP_BODY;
}
}
解説
カスタムタグ処理クラスはTagSupportクラスを継承したクラスにします。
public class EasyCustom extends TagSupport {
setPageContext()メソッドを実装します。引数で与えられたPageContextを保持します。
public void setPageContext(PageContext pc) {
this.pc = pc;
}
doStartTag()を実装します。
public int doStartTag() throws JspException {
PageContextからgetOut()メソッドを呼び出し、JspWriterを取得します。
JspWriter out = pc.getOut();
"Hello Easy Custom World !!"文字列を出力します
out.println("Hello Easy Custom World !!");
BODYの処理をスキップする戻り値SKIP_BODYを返してメソッドを終了します。
return SKIP_BODY;
実行結果
カスタムタグが処理され、"Hello Easy Custom World !!"の文字列が画面に出力されます。
著者
iPentecのプログラマー、最近はAIの積極的な活用にも取り組み中。
とっても恥ずかしがり。
最終更新日: 2024-01-06
作成日: 2011-02-12