マイペースなプログラミング日記

DTMやプログラミングにお熱なd-kamiがマイペースに書くブログ

TimerEvent その1 AjaxSelfUpdatingTimerBehavior

Wicketにあるタイマーイベントの一つAjaxSelfUpdatingTimerBehaviorを使った簡単なWebアプリを作ってみた。AjaxSelfUpdatingTimerBehaviorは追加されたコンポーネントを一定時間毎に更新してくれるイベント。以下ソース

まずはHTML、ファイルはTimerEventPage.html

<html>
  <head>
    <title>Timer</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body>
    <span wicket:id="timer"></span>
  </body>
</html>

次に対応するJavaのソース、TimerEventPage.java

package timer;

import java.util.Date;
import java.text.SimpleDateFormat;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.ajax.AjaxSelfUpdatingTimerBehavior;
import org.apache.wicket.util.time.Duration;

public class TimerEventPage extends WebPage{
    public TimerEventPage(){
        IModel<String> timerModel = new AbstractReadOnlyModel<String>(){
            public String getObject(){
                Date date = new Date();
                SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
                return format.format(date);
            }
        };

        Label label = new Label("timer", timerModel);
        label.add(new AjaxSelfUpdatingTimerBehavior(Duration.seconds(1)));
        
        add(label);
    }
}

次にアプリケーションクラス、TimerEventApplication

package timer;

import org.apache.wicket.protocol.http.WebApplication;

public class TimerEventApplication extends WebApplication{
    public Class<TimerEventPage> getHomePage(){
        return TimerEventPage.class;
    }
    
    public void init(){
       getRequestCycleSettings().setResponseRequestEncoding("UTF-8");
        getMarkupSettings().setDefaultMarkupEncoding("UTF-8");
    }
}

最後にフィルタマッピング

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <filter>
        <filter-name>TimerEvent</filter-name>
        <filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
        <init-param>
            <param-name>applicationClassName</param-name>
            <param-value>timer.TimerEventApplication</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>TimerEvent</filter-name>
        <url-pattern>/timer/*</url-pattern>
    </filter-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>