目次へ

解答例 - 実習課題1 - 20.メニューの作成

(実習課題1)

以下のWebアプリケーションを、Tilesを用いて作成しなさい。

  • 以下のレイアウトで表示すること
    メニュー コンテンツ
  • コンテンツ部分に表示するTileは、「現在の月のカレンダーを表示するもの」「世界各地の現在時刻を表示するもの」「天気予報(予報内容についてはランダムで良い)」とすること。
  • メニュー部分には、それぞれのコンテンツを表示するためのリンクを一覧として表示すること。ただし現在表示されているコンテンツを表示するものへのリンクは除くこと。

解答例

▼ディレクトリ構成は以下の通り

.
└─WEB-INF              web.xml,struts-config.xml,tiles-defs.xml
    ├─classes
    │  └─com
    │      └─techscore
    │          └─struts       EncodingFilter.class(2章 実習課題2と同じ),
    │             │            MessageResources.properties(空ファイル)
    │             └─chapter20
    │                  └─exercise1 CalendarTag.class
    ├─JSP
    │  └─com
    │      └─techscore
    │          └─struts
    │              └─chapter20
    │                  └─exercise1 calendar.jsp,calendarPlus.jsp,clock.jsp,weather.jsp
    ├─lib              strutsライブラリ jarファイル
    └─tld              original.tld,struts-tiles.tld,struts-html.tld,struts-beans.tld,struts-logic.tld



※strutsライブラリjarファイル
  struts.jar,commons-beanutils.jar,commons-collections.jar,commons-digester.jar,commons-logging.jar,jakarta-oro.jar
/**
 * CalendarTag.java
 * TECHSCORE Java JakartaStruts 20章 
 *
 * Copyright (c) 2004 Four-Dimensional Data, Inc.
 *
 */

package com.techscore.struts.chapter20.exercise1;

import javax.servlet.jsp.tagext.TagSupport;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.JspException;
import java.io.IOException;

import java.util.Calendar;


public class CalendarTag extends TagSupport {
    private String year = "";
    private String month = "";

    private final int DAYS_WEEK = 7;  //週の日数
    private final String COLOR_SUNDAY = "pink";      //日曜日の色
    private final String COLOR_SATURDAY = "skyblue";   //土曜日の色

    public void setYear(String year) {
        this.year = year;
    }

    public void setMonth(String month) {
        this.month = month;
    }

    public int doStartTag() throws JspException {

        try {
            int intYear;
            int intMonth;

            JspWriter writer = pageContext.getOut();

            //パラメータが数字かどうかチェック
            try {
                intYear = Integer.parseInt(this.year);
                intMonth = Integer.parseInt(this.month);
            } catch (NumberFormatException e) {
                writer.print("パラメータが数字以外のため表示できません");
                return SKIP_BODY;
            }

            //月が1から12かどうかチェック
            if ((intMonth < 1) || (intMonth > 12)) {
                writer.print("月が1から12以外のため表示できません");
                return SKIP_BODY;
            }

            writer.println("<h3>" + intYear + "年" + intMonth + "月</h3>");

            //一番上の曜日部分を作成
            writeHeader(writer);

            Calendar calendar = Calendar.getInstance();
            calendar.set(intYear, intMonth - 1, 1);

            //月初の曜日をもとに月初までの空部分を作成
            //※初日が日曜でない場合のみこの処理が必要
            int weekOfFirstDay =calendar.get(Calendar.DAY_OF_WEEK);
            if (weekOfFirstDay != Calendar.SUNDAY) {
                writer.print("<tr>");
                for (int i = 1; i < weekOfFirstDay; i++) {
                    writer.print("<td></td>");
                }
            }

            //末日まで作成
            int endDay = calendar.getActualMaximum(Calendar.DATE);
            while ((calendar.get(Calendar.DATE) <= endDay) &&
                   (calendar.get(Calendar.MONTH) == intMonth - 1)) {
                int week = calendar.get(Calendar.DAY_OF_WEEK);
                if ( week == Calendar.SUNDAY ) {
                    writer.print("<tr><td align=\"center\" bgcolor=" + COLOR_SUNDAY + ">");
                } else if ( week == Calendar.SATURDAY ) {
                    writer.print("<td align=\"center\" bgcolor=" + COLOR_SATURDAY + ">");
                } else {
                    writer.print("<td align=\"center\">");
                }
                writer.print(calendar.get(Calendar.DATE) + "</td>");
                if ( week == Calendar.SATURDAY ) {
                    writer.println("</tr>");
                }
                calendar.add(Calendar.DATE, 1);
            }

            //末日の曜日をもとに末日以降の空部分を作成
            //※末日が土曜でない場合のみこの処理が必要
            calendar.add(Calendar.DATE, -1);
                //上のwhile文で末日+1になっているので戻す
            int weekOfEndDay = calendar.get(Calendar.DAY_OF_WEEK);
            if (weekOfEndDay != Calendar.SATURDAY) {
                for (int j = 1; j <= DAYS_WEEK - calendar.get(Calendar.DAY_OF_WEEK); j++) {
                    writer.print("<td></td>");
                }
                writer.println("</tr>");
            }

            writer.println("</table>");
        } catch (IOException e) {
            throw new JspException(e);
        }
        return SKIP_BODY;
    }

    public int doEndTag() throws JspException {
       return EVAL_PAGE;
    }


    //カレンダーの曜日部分を作成
    private void writeHeader(JspWriter writer) throws JspException {

        try {
            writer.println("<table border=\"2\" width=\"100%\">");
            writer.print("<tr><td align=\"center\" bgcolor=" + COLOR_SUNDAY + ">日</td>");
            writer.print("<td align=\"center\">月</td>");
            writer.print("<td align=\"center\">火</td>");
            writer.print("<td align=\"center\">水</td>");
            writer.print("<td align=\"center\">木</td>");
            writer.print("<td align=\"center\">金</td>");
            writer.println("<td align=\"center\" bgcolor=" + COLOR_SATURDAY + ">土</td></tr>");
        } catch (IOException e) {
            throw new JspException(e);
        }

    }

}
<!-- calendar.jsp -->
<!-- TECHSCORE Java JakartaStruts 20章 実習課題1 -->
<!-- Copyright (c) 2004 Four-Dimensional Data, Inc. -->

<%@ page pageEncoding="Windows-31J"
         import="java.util.Calendar" %>

<%@ taglib uri="http://www.4dd.co.jp/tags/original"
    prefix="original" %>

<h2 align="center">カレンダー</h2>

<% Calendar calendar = Calendar.getInstance(); %>

<original:Calendar year="<%=Integer.toString(calendar.get(Calendar.YEAR)) %>"
                   month="<%=Integer.toString(calendar.get(Calendar.MONTH) + 1) %>" />
<!-- calendarPlus.jsp -->
<!-- TECHSCORE Java JakartaStruts 20章 実習課題1 -->
<!-- Copyright (c) 2004 Four-Dimensional Data, Inc. -->

<%@ page contentType="text/html; charset=Windows-31J"
         session="false" 
         pageEncoding="Windows-31J" %>

<%@ taglib uri="http://jakarta.apache.org/struts/tags-html"
           prefix="html" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean"
           prefix="bean" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-logic"
           prefix="logic" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-tiles"
           prefix="tiles" %>

<html:html>
<head><title>TECHSCORE Java JakartaStruts 20章 実習課題1</title></head>
<body>

<table border="1" width="100%">
    <tr>
        <!-- メニュー部分-->
        <td align="center" width="30%">
            <h3>MENU</h3>
            <tiles:importAttribute name="menuList" />
            <logic:iterate id="menu" name="menuList"
                           type="org.apache.struts.tiles.beans.SimpleMenuItem">
                <bean:define id="linkPath" name="menu" property="link" type="java.lang.String" />
                <html:link page="<%=linkPath %>">
                    <p><bean:write name="menu" property="value" /></p>
                </html:link>
            </logic:iterate>
        </td>
        <!-- コンテンツ部分-->
        <td align="center"><tiles:insert attribute="content" /></td>
    </tr>
</table>

</body>
</html:html>
<!-- clock.jsp -->
<!-- TECHSCORE Java JakartaStruts 20章 実習課題1 -->
<!-- Copyright (c) 2004 Four-Dimensional Data, Inc. -->

<%@ page pageEncoding="Windows-31J"
         import="java.text.DateFormat,
                  java.text.SimpleDateFormat,
                  java.util.Date,
                  java.util.TimeZone" %>

<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean"
           prefix="bean" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-logic"
           prefix="logic" %>

<%  String[] cities = {"Japan",
 		                   "America/Los-Angeles",
 		                   "America/New_York",
 		                   "Europe/Moscow",
 		                   "Pacific/Saipan"}; %>

<h2 align="center">世界時計</h2>

<%  DateFormat dateFormat = new SimpleDateFormat("MM/dd HH:mm:ss"); %>
<table border="1" width="100%">
    <logic:iterate collection="<%=cities %>" id="city" indexId="index">
        <tr><td align="center">
                <bean:write name="city" />
            </td>
            <td align="center">
                <bean:define id="zoneName" name="city" type="java.lang.String" />
                <%  dateFormat.setTimeZone(TimeZone.getTimeZone(zoneName)); %>
                <%=dateFormat.format(new Date()) %>
            </td></tr>
    </logic:iterate>
</table>
<!-- weather.jsp -->
<!-- TECHSCORE Java JakartaStruts 20章 実習課題1 -->
<!-- Copyright (c) 2004 Four-Dimensional Data, Inc. -->

<%@ page pageEncoding="Windows-31J" %>

<h2 align="center">天気予報</h2>

<table border="1" width="100%">
    <tr><td align="center">Tokyo</td><td align="center">晴れ</td></tr>
    <tr><td align="center">Los-Angeles</td><td align="center">晴れ時々曇り</td></tr>
    <tr><td align="center">New_York</td><td align="center">雨のち曇り</td></tr>
    <tr><td align="center">Moscow</td><td align="center">曇りのち晴れ</td></tr>
    <tr><td align="center">Saipan</td><td align="center">晴れのち曇り</td></tr>
</table>

▼original.tld

<?xml version="1.0" ?>
<!DOCTYPE taglib
  PUBLIC
  "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
  "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">

<taglib>
    <tlib-version>1.0</tlib-version>
    <jsp-version>1.2</jsp-version>
    <short-name>original tags</short-name>

    <tag>
        <name>Calendar</name>
        <tag-class>com.techscore.struts.chapter20.exercise1.CalendarTag</tag-class>
        <body-content>empty</body-content>
        <attribute>
            <name>year</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
        <attribute>
            <name>month</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
    </tag>

</taglib>

▼tiles-defs.xml

<?xml version="1.0" encoding="Windows-31J" ?>
<!DOCTYPE tiles-definitions PUBLIC
  "-//Apache Software Foundation//DTD Tiles Configuration//EN"
  "http://jakarta.apache.org/struts/dtds/tiles-config_1_1.dtd">
  
<tiles-definitions>

    <definition name="calendar201"
                path="/WEB-INF/JSP/com/techscore/struts/chapter20/exercise1/calendarPlus.jsp">
        <put name="content" value="/WEB-INF/JSP/com/techscore/struts/chapter20/exercise1/calendar.jsp" />
        <putList name="menuList">
            <item value="世界時計"   link="/com/techscore/struts/chapter20/exercise1/CalendarPlus_clock.do" />
            <item value="天気予報"   link="/com/techscore/struts/chapter20/exercise1/CalendarPlus_weather.do" />
        </putList>
    </definition>

    <definition name="clock201"
                path="/WEB-INF/JSP/com/techscore/struts/chapter20/exercise1/calendarPlus.jsp">
        <put name="content" value="/WEB-INF/JSP/com/techscore/struts/chapter20/exercise1/clock.jsp" />
        <putList name="menuList">
            <item value="カレンダー" link="/com/techscore/struts/chapter20/exercise1/CalendarPlus_calendar.do" />
            <item value="天気予報"   link="/com/techscore/struts/chapter20/exercise1/CalendarPlus_weather.do" />
        </putList>
    </definition>

    <definition name="weather201"
                path="/WEB-INF/JSP/com/techscore/struts/chapter20/exercise1/calendarPlus.jsp">
        <put name="content" value="/WEB-INF/JSP/com/techscore/struts/chapter20/exercise1/weather.jsp" />
        <putList name="menuList">
            <item value="カレンダー" link="/com/techscore/struts/chapter20/exercise1/CalendarPlus_calendar.do" />
            <item value="世界時計"   link="/com/techscore/struts/chapter20/exercise1/CalendarPlus_clock.do" />
        </putList>
    </definition>

</tiles-definitions>

▼struts-config.xml

<?xml version="1.0" encoding="Windows-31J" ?>
<!DOCTYPE struts-config PUBLIC
  "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
  "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>

    <action-mappings>

        <action path="/com/techscore/struts/chapter20/exercise1/CalendarPlus_calendar"
                forward="calendar201" />

        <action path="/com/techscore/struts/chapter20/exercise1/CalendarPlus_clock"
                forward="clock201" />

        <action path="/com/techscore/struts/chapter20/exercise1/CalendarPlus_weather"
                forward="weather201" />

    </action-mappings>

    <message-resources parameter="com.techscore.struts.MessageResources" />

    <plug-in className="org.apache.struts.tiles.TilesPlugin">
        <set-property property="definitions-config"
                      value="/WEB-INF/tiles-defs.xml" />
    </plug-in>

</struts-config>

▼web.xml

<?xml version="1.0" encoding="Windows-31J" ?>
<!DOCTYPE web-app PUBLIC
  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  "http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">

<!-- Copyright (c) 2002 by ObjectLearn. All Rights Reserved. -->
<web-app>

    <filter>
        <filter-name>Encoding</filter-name>
        <filter-class>com.techscore.struts.EncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>Windows-31J</param-value>
        </init-param>
    </filter>
    
    <filter-mapping>
        <filter-name>Encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>Action</servlet-name>
        <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
        <init-param>
            <param-name>config</param-name>
            <param-value>/WEB-INF/struts-config.xml</param-value>
        </init-param>
        <init-param>
            <param-name>debug</param-name>
            <param-value>6</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Action</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <taglib>
        <taglib-uri>http://jakarta.apache.org/struts/tags-bean</taglib-uri>
        <taglib-location>/WEB-INF/tld/struts-bean.tld</taglib-location>
    </taglib>

    <taglib>
        <taglib-uri>http://jakarta.apache.org/struts/tags-html</taglib-uri>
        <taglib-location>/WEB-INF/tld/struts-html.tld</taglib-location>
    </taglib>

    <taglib>
        <taglib-uri>http://jakarta.apache.org/struts/tags-logic</taglib-uri>
        <taglib-location>/WEB-INF/tld/struts-logic.tld</taglib-location>
    </taglib>

    <taglib>
        <taglib-uri>http://jakarta.apache.org/struts/tags-tiles</taglib-uri>
        <taglib-location>/WEB-INF/tld/struts-tiles.tld</taglib-location>
    </taglib>

    <taglib>
        <taglib-uri>http://www.4dd.co.jp/tags/original</taglib-uri>
        <taglib-location>/WEB-INF/tld/original.tld</taglib-location>
    </taglib>

</web-app>

▼起動URLは以下の通り

WEB_ROOT/com/techscore/struts/chapter20/exercise1/CalendarPlus_calendar.do
WEB_ROOT/com/techscore/struts/chapter20/exercise1/CalendarPlus_clock.do
WEB_ROOT/com/techscore/struts/chapter20/exercise1/CalendarPlus_weather.do

EncodingFilter.javaの参照(2章の実習課題2と同じ)


↑このページの先頭へ

こちらもチェック!

PR
  • XMLDB.jp