タグライブラリの利用例 (現在日時を表示するタグ) - JSP

現在の日時を表示するタグライブラリのコードです。

コード (jspファイル:getdate.jsp)

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ taglib uri="/DateLibrary" prefix="gd" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
  </head>
  <body>
    <h1>JSP Page</h1>
    <gd:getDate/>
  </body>
</html>

コード (date.tld)

<?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.0</tlib-version>
  <short-name>date</short-name>
  <uri>/WEB-INF/tlds/date</uri>
  <tag>
    <name>getDate</name>
    <tag-class>webApplication23.GetDateHandler</tag-class>
  </tag>
</taglib>

コード (タグ処理クラス:GetDateHandler.java)

package webApplication23;

import java.util.Date;
import java.text.DateFormat;

import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;

public class GetDateHandler extends TagSupport {

  private PageContext pc = null;

  public void setPageContext(PageContext pc) {
    this.pc = pc;
  }

  /** Creates a new instance of GetDateHandler */
  public GetDateHandler() {
  }

  public int doStartTag() throws JspException {
    //JSPに対する出力ストリームの取得
    JspWriter out = pc.getOut();

    DateFormat df = DateFormat.getTimeInstance(DateFormat.LONG);
    Date date = new Date();

    try {
      out.println(df.format(date));
    } catch (Exception e) {
      throw new JspException(e);
    }
    //BODY処理をスキップ
    return SKIP_BODY;
  }
}

解説

public void setPageContext(PageContext pc) {
  this.pc = pc;
}
setPageContext()メソッドを実装します。引数で与えられたPageContextをメンバ変数に保存します。

JspWriter out = pc.getOut();
PageContext.getOut()メソッドを呼び出し、JspWriterを取得します。

DateFormat df = DateFormat.getTimeInstance(DateFormat.LONG);
Date date = new Date();
try {
  out.println(df.format(date));
} catch (Exception e) {
  throw new JspException(e);
}
DataFormatと現在の時刻を示すDateインスタンスを取得し、現在の日時の文字列を画面に出力します。

コード (web.xml)

<?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">
  <jsp-config>
    <taglib>
      <taglib-uri>/DateLibrary</taglib-uri>
      <taglib-location>/WEB-INF/tlds/date.tld</taglib-location>
    </taglib>
  </jsp-config>
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

実行結果

現在の時刻が表示されます。


著者
iPentecのプログラマー、最近はAIの積極的な活用にも取り組み中。
とっても恥ずかしがり。
最終更新日: 2024-01-06
作成日: 2011-02-14
iPentec all rights reserverd.