Develop a simple Web application with Apache Wicket · PDF fileDevelop a simple Web...

27
Develop a simple Web application with Apache Wicket and Apache Geronimo Combine Wicket, Geronimo, and Apache Derby to form an open source Java Web development platform Skill Level: Intermediate Robi Sen ([email protected]) Vice President Department 13 LLC 10 Jul 2007 Apache Wicket is an innovative Java™ Web application framework that was introduced a couple of years ago. It helps simplify Web application development by clearly separating the roles of developers and designers. It lets you remove logical code from the view layer, eliminating the need for JavaServer Pages (JSP), providing a simple plain old Java object (POJO)-centric mode of development, and removing much of the need for XML and other configuration file formats. In this tutorial, learn how to set up your system to develop a simple Web application with Wicket, using Apache Geronimo as your application server and Apache Derby as the embedded database. Section 1. Before you start This tutorial is designed for developers who have found Java frameworks, such as Struts, lacking in needed functionality. If you're interested in developing Web applications in a more object-oriented manner, where the view is clearly separated from logic and there's minimal configuration and mapping, then Wicket is for you! This tutorial walks you through the basics of how Wicket works, while using Apache Geronimo to set up a Java Platform, Enterprise Edition (Java EE) server, Web server, and embedded database in just minutes. Combining Wicket with Geronimo lets you develop data-driven, scalable Web applications using software that's all open source. Develop a simple Web application with Apache Wicket and Apache Geronimo © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 27

Transcript of Develop a simple Web application with Apache Wicket · PDF fileDevelop a simple Web...

Develop a simple Web application with ApacheWicket and Apache GeronimoCombine Wicket, Geronimo, and Apache Derby to form an opensource Java Web development platform

Skill Level: Intermediate

Robi Sen ([email protected])Vice PresidentDepartment 13 LLC

10 Jul 2007

Apache Wicket is an innovative Java™ Web application framework that wasintroduced a couple of years ago. It helps simplify Web application development byclearly separating the roles of developers and designers. It lets you remove logicalcode from the view layer, eliminating the need for JavaServer Pages (JSP), providinga simple plain old Java object (POJO)-centric mode of development, and removingmuch of the need for XML and other configuration file formats. In this tutorial, learnhow to set up your system to develop a simple Web application with Wicket, usingApache Geronimo as your application server and Apache Derby as the embeddeddatabase.

Section 1. Before you start

This tutorial is designed for developers who have found Java frameworks, such asStruts, lacking in needed functionality. If you're interested in developing Webapplications in a more object-oriented manner, where the view is clearly separatedfrom logic and there's minimal configuration and mapping, then Wicket is for you!

This tutorial walks you through the basics of how Wicket works, while using ApacheGeronimo to set up a Java Platform, Enterprise Edition (Java EE) server, Webserver, and embedded database in just minutes. Combining Wicket with Geronimolets you develop data-driven, scalable Web applications using software that's allopen source.

Develop a simple Web application with Apache Wicket and Apache Geronimo© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 27

About this tutorial

Developing Java Web applications can be awkward and frustrating. For yearsdevelopers have tried to solve problems with Java application development bycreating frameworks that solve specific problems. But few have been able to simplifyWeb development, separate roles, clearly separate the view from the model andremove special markup, and define a totally POJO-centric model of development —until now. Enter Apache Wicket.

Wicket, an innovative Java Web application framework introduced a couple of yearsago, simplifies Web application development by clearly separating roles ofdevelopers and designers, in part by removing logical code from the view layer. Thissimple and pure approach to Model-View-Controller (MVC) development, coupledwith its simple development workflow that lacks XML configuration files, makeWicket a powerful and enjoyable development framework. It solves a number ofdevelopment challenges, allowing you to focus more on functionality and less on theapplication configuration.

In this tutorial, you zero in on how to set up and configure a project to use the Wicketframework with Databinder, which allows Wicket and Hibernate to work nicelytogether. You combine these applications with the Apache Derby embeddeddatabase to create a simple Web application in record time. From there, you learnhow to deploy your application on Geronimo.

System requirements

You need the following tools to follow along with this tutorial:

• Apache Geronimo 2.0-M2 with Tomcat 6 — Geronimo is the Java EEapplication server that you deploy to.

• An operating system — This application was developed usingMicrosoft® Windows® XP, but everything involved has been widely usedon Linux® and OS X. So you should be able to follow the tutorial usingplatforms other than Windows.

• Java JDK 1.5 or later — Java 1.5_11 was used to develop all the code inthis tutorial, but 1.5 and later JDKs should work.

• Embedded database — This tutorial uses Apache Derby, the lightweight,100% Java-based database. Because Geronimo already has Derby builtin, you don't need to download anything.

• Eclipse — In this tutorial, you use Eclipse 3.2 as the IDE. It's notrequired, but it greatly simplifies your development process.

• Apache Maven 2 — You use Maven 2 in this project to automaticallygather required files and build projects.

developerWorks® ibm.com/developerWorks

Develop a simple Web application with Apache Wicket and Apache GeronimoPage 2 of 27 © Copyright IBM Corporation 1994, 2008. All rights reserved.

• Databinder — A lightweight utility written by Nathan Hamblen,Databinder is a tool that lets Wicket and Hibernate work togetherextremely well, greatly simplifying development of data-driven Wicketapplications.

Section 2. Setting the stage

Few Java Web application developers would argue that developing Java Webapplications is a straightforward, simple-to-manage, and delightful process. OftenJava Web application frameworks, while solving many problems, end up being brittleand difficult to change after their initial development. Furthermore, many frameworks— while espousing separation of concerns and decoupling of logic from presentation— often mix logic and presentation, thus forcing developers to manage overlycomplex XML files used in configuration and mapping.

Wicket solves all of these problems in a novel and elegant way by using only plainHTML on the view layer and POJOs for everything else. Wicket in part solves thisproblem by extending HTML in a compliant way by introducing the Wicketnamespace (wicket:id), which allows Wicket to map specific dynamic functionality toareas of your Web site and associate them with specific models represented by aJava class and subclasses.

For most people, the easiest way to learn is by doing, so let's set up an environmentand start building your Wicket application. To get started, you need to downloadMaven 2, which you use to streamline the setup and creation of your Wicket project.You also need to download and set up Geronimo, and finally, if you're not alreadyusing it, Eclipse. Download links are available in the System requirements section.

Install Java 1.5

Before you do anything, make sure you have Java JDK 1.5 installed on your systemand the environment variables PATH pointing to your JDK bin directory. You mustalso have the Java environment variable JAVA_HOME pointing to your Java installdirectory.

Set up Geronimo

For this tutorial, you use Apache Geronimo not only as your Java application server,but also as your database server. Geronimo is a fully compliant Java 2 Platform,Enterprise Edition (J2EE)-certified server that includes an implementation of aservlet container, an Enterprise JavaBeans (EJB) container, a Java MessageService (JMS) provider, a J2EE Connector architecture (JCA) container, and thelightweight Derby database, all licensed under the Apache license.

ibm.com/developerWorks developerWorks®

Develop a simple Web application with Apache Wicket and Apache Geronimo© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 3 of 27

Setting up Geronimo is simple. To install it:

1. Download it, and unpack it to a directory. For this example, you useC:\geronimo, but you can unpack it anywhere you want.

2. After it's unpacked, there are two ways you can start Geronimo:

• Go to the bin directory where you placed Geronimo, which in thiscase is C:\geronimo\bin, and type java -jar server.jar.

• Simply call the startup.bat in the bin directory, or double-click it.The Geronimo server should now start up.

3. After it's started, you can test that everything is working correctly by goingto http://localhost:8080/, where you should see something like Figure 1.Figure 1. Successful startup of the Geronimo server

Note: The Geronimo server will want to use port 8080 for the server, and

developerWorks® ibm.com/developerWorks

Develop a simple Web application with Apache Wicket and Apache GeronimoPage 4 of 27 © Copyright IBM Corporation 1994, 2008. All rights reserved.

if you know that port is already being used, you'll need to edit theconfig.xml file, which you can find in C:\geronimo\var\config. For moreinformation about installing Geronimo, refer to the Apache Geronimo wiki(see Resources for a link).

Now that you have Geronimo working, it's time to use Maven to set up yourenvironment for working with Wicket.

Install and test Maven 2

For this tutorial to help you set up and configure your projects, you're going to useMaven 2 (see System requirements for a link). Maven is a software-managementtool that provides a wealth of functionality, from helping manage dependencies toproviding project reporting. You need to be connected to the Internet while usingMaven.

1. Get the Maven binary (see System requirements for a link), and install the2.0.7 binary according to the instructions.

2. To test it, open a command prompt, and type mvn -version. Youshould see something like Maven version: 2.0.7.

Now you need to download all the prerequisite JAR files for your project and set upthe initial Wicket project. Almost everything you need for this tutorial is automaticallydownloaded by Maven, except for two JAR files. One is the Sun Java TransactionAPI (JTA), which, for licensing reasons, can't be held there.

3. For this file, you need to go to the Sun JTA page, select Class Files1.0.1B, and download it.

4. After it's downloaded, navigate to that download directory, and either typeor paste the code shown in Listing 1 into a command shell prompt.Listing 1. Adding Sun JTA to your local Maven repository

mvn install:install-file -DgroupId=javax.transaction-DartifactId=jta-Dversion=1.0.1B -Dpackaging=jar -Dfile=jta-1_0_1B-classes.zip

This should add the JTA to your local Maven repository. Now you need to set up andcreate a Databinder project. Databinder is the toolkit that makes working withHibernate and Derby from Wicket much easier (see System requirements for a link).

5. To create the Databinder project, type or paste the commands in thecommand prompt (see Listing 2) in a directory in which you want to create

ibm.com/developerWorks developerWorks®

Develop a simple Web application with Apache Wicket and Apache Geronimo© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 5 of 27

the new project. For this tutorial, I assume you'll use c:\projects, but youcan do this anywhere in your file system.Listing 2. Create the Databinder project

mvn archetype:create -DarchetypeGroupId=net.databinder-DarchetypeArtifactId=data-app-DarchetypeVersion=1.0 -DgroupId=developerworks-DartifactId=ToDo

Note: The DartificatId is essentially what you want your project to becalled, and the DgroupId is usually something unique, such as yourcompany, organization, or domain name.

You should see something like Figure 2 when your project is created.

Figure 2. Databinder archetype being created by Maven 2

developerWorks® ibm.com/developerWorks

Develop a simple Web application with Apache Wicket and Apache GeronimoPage 6 of 27 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Now that your resources and project have been set up, you can move on to the nextsection where you configure your project to easily import it into Eclipse.

ibm.com/developerWorks developerWorks®

Develop a simple Web application with Apache Wicket and Apache Geronimo© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 7 of 27

Set up Eclipse

Now that the archetype is created, you can set it up so you can work with it fromEclipse. Here I assume you're using Eclipse 3.2, but 3.1 should work fine.

1. To prepare this project to be imported into Eclipse, you need to first addthe Maven repository to your Eclipse workspace (here I'm assuming it's inC:\projects), like this: mvn -Declipse.workspace=/projectseclipse:add-maven-repo.

2. Now tell Maven to get all of the Databinder dependencies, source, and soon by first changing the ToDo directory that was created previously whenyou created the project, and either typing or pasting the followingcommand: mvn -Declipse.downloadSources=trueeclipse:eclipse. This may take a while, depending on your Internetconnection, because Maven downloads all the files and dependenciesyou need to a local repository so that you can build your application later.You should see something like Figure 3.Figure 3. Maven downloading and configuring the ToDo projectbefore importing into Eclipse

developerWorks® ibm.com/developerWorks

Develop a simple Web application with Apache Wicket and Apache GeronimoPage 8 of 27 © Copyright IBM Corporation 1994, 2008. All rights reserved.

3. When the download is complete, start Eclipse, and choose File > Import.

4. Select Existing Projects into Workspace, then select the ToDo

ibm.com/developerWorks developerWorks®

Develop a simple Web application with Apache Wicket and Apache Geronimo© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 9 of 27

directory. This should add the ToDo project to your Eclipse IDE.

In the next section, you make a few more changes to your configuration so that youcan get started developing the Wicket application.

Final steps

You have only a few more steps to complete before you can start development:

1. Add a directory called lib under ToDo\src\main\webapp\WEB-INF, andplace a copy of the derbyclient.jar (which can be found inC:\geronimo\repository\org\apache\derby\derbyclient\10.2.2.0) in thedirectory.

2. Edit the hibernate.properties file found inToDo\src\main\java\developerworks so that it looks like Listing 3. This isnecessary for Hibernate to interact with Derby.Listing 3. Edit the hibernate.properties file

hibernate.dialect=org.hibernate.dialect.DerbyDialecthibernate.connection.driver_class=org.apache.derby.jdbc.ClientDriverhibernate.connection.url=jdbc:derby://localhost:1527/ToDo;create=truehibernate.connection.username=adminhibernate.connection.password=admin

3. Go to ToDo\target and open pom.xml with the text editor option inEclipse. Make sure you have the code from Listing 4 added to yourpom.xml file, and make sure your pom.xml file looks like Listing 5.Listing 4. Dependency

<dependency><groupId>org.apache.derby</groupId><artifactId>derby</artifactId><version>10.2.2.0</version>

</dependency>

Listing 5. Updated pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0

http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>developerworks</groupId><artifactId>ToDo</artifactId><build>

<plugins><plugin>

<groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId>

<configuration>

developerWorks® ibm.com/developerWorks

Develop a simple Web application with Apache Wicket and Apache GeronimoPage 10 of 27 © Copyright IBM Corporation 1994, 2008. All rights reserved.

<source>1.5</source><target>1.5</target>

</configuration></plugin><plugin>

<groupId>org.mortbay.jetty</groupId><artifactId>maven-jetty-plugin</artifactId><configuration>

<scanIntervalSeconds>10</scanIntervalSeconds><systemProperties>

<systemProperty><name>org.apache.commons.logging.Log</name><value>org.apache.commons.logging.impl.

SimpleLog</value></systemProperty>

</systemProperties></configuration>

</plugin><plugin>

<artifactId>maven-release-plugin</artifactId><configuration>

<tagBase>svn://localhost/todo/</tagBase></configuration>

</plugin></plugins><resources>

<resource><directory>src/main/java</directory><includes>

<include>**</include></includes><excludes>

<exclude>**/*.java</exclude></excludes>

</resource></resources>

</build><packaging>war</packaging><version>1.0-SNAPSHOT</version><name>Databinder Application</name><dependencies>

<dependency><groupId>net.databinder</groupId><artifactId>databinder</artifactId><version>1.0</version>

</dependency><dependency>

<groupId>org.apache.derby</groupId><artifactId>derby</artifactId><version>10.2.2.0</version>

</dependency></dependencies>

<!-- uncomment to download prerelease versions of Databinder<repositories>

<repository><id>databinder-snapshots</id><name>Databinder snapshot repository</name><url>http://databinder.net/snapshot</url>

</repository></repositories>

--></project>

Now that your development environment is set up and ready, take a quick look athow Wicket works, then you can build a simple data-driven Web application.

ibm.com/developerWorks developerWorks®

Develop a simple Web application with Apache Wicket and Apache Geronimo© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 11 of 27

Section 3. Build the Wicket application

At the heart of Wicket is the idea of separation of concerns between Java code andHTML code, and between coders and designers. Wicket does this by associatingJava and HTML in parallel via a Wicket HTML namespace extension, or a Wicket ID.In this section, you build a simple application that uses Wicket as your framework;Hibernate and Databinder to abstract persistence; and Geronimo as your applicationserver, database server, and Web server.

The ToDo layout

For your Wicket example, you're going to create a simple to-do list application.Generally, with small Web applications, a designer creates the overall design of theapplication in HTML. So for your application, assume that a designer has alreadyprovided you with the HTML, CSS, and other resources for a static site, which youuse later. The designer might create something that looks like Figure 4.

Figure 4. Prototype design for your Wicket site

Keep in mind that the application needs to let the user add or delete a simple taskthat has a name or description. The tasks should then be displayed in two columnsunder the ToDo list text.

Now your job is to create the ToDo list application with these simple requirements inmind. To do that, you first need to create a Wicket application.

developerWorks® ibm.com/developerWorks

Develop a simple Web application with Apache Wicket and Apache GeronimoPage 12 of 27 © Copyright IBM Corporation 1994, 2008. All rights reserved.

The Wicket application

As an application developer, your job is to create the Java components that let theapplication post new tasks, delete tasks, or whatever else you decide the applicationneeds.

Wicket applications usually start with implementation of the Web Applicationclass. In this application, however, you first extend DataApplication, which is aDatabinder extension for Wicket that functions the same way as the WebApplication class, but lets you leverage Hibernate to map your Task objects tothe database.

In this initial class, you create an Application object that lets you describe theorganization and configuration of the application. It also lets you define the Javaclass, which defines the page functionality for the HTML template. Wicket Webpages are all Java classes that map to an HTML template, with the same name asthe Java class, which you'll see in a later section.

Wicket Application classes are named using a simple convention likeYourApplicationNameApplication.java.

1. Go to Eclipse, and navigate to the ToDo\src\main\java\developerworksdirectory, where you'll see that Maven has already created example JavaWicket classes for you.

2. You can either delete them or rename the MyApplication.java classto ToDoApplication.java.

3. Type or paste the code in Listing 6 into Eclipse, and save it.Listing 6. ToDoApplication.java

package developerworks;

import net.databinder.DataApplication;import org.hibernate.cfg.AnnotationConfiguration;

public class ToDoApplication extends DataApplication {

/*** @return Page to display when no specific page is

requested* ListAndAdd class is the Java class, which needs to map

to an HTML* template named ListAndAdd.html*/@Overridepublic Class getHomePage() {

return ListAndAdd.class;}

/*** Add annotated classes to config, leaving the call to

super-implementation* in most cases.* @param config Hibernate configuration*/

ibm.com/developerWorks developerWorks®

Develop a simple Web application with Apache Wicket and Apache Geronimo© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 13 of 27

/** Set default configuration and mapping for Tasks. */protected void configureHibernate(AnnotationConfiguration

config) {super.configureHibernate(config);config.addAnnotatedClass(Task.class);

}

Note the reference to ListAndAdd.class and Task.class.ListAndAdd.class is going to be the home page, and, as stated earlier, WicketWeb pages are all Java classes that map to an HTML template with the same name.In this Application class, you're telling Wicket via the getHomePage method thatthis is the application's home page. All initial requests to the application call the Javaobject ListAndAdd and render HTML based on ListAndAdd.html.

Listing 7 configures Hibernate to map the Task object to the database.

Listing 7. Configuring Hibernate to map the Task object to the database

protected void configureHibernate(AnnotationConfigurationconfig) {

super.configureHibernate(config);config.addAnnotatedClass(Task.class);

}

Task, in this case, is an object that represents one of the to-do items that you wantto persist in Derby. With that in mind, you can create a Task class.

The Task class

Looking at Figure 4, note that you have a simple form for your to-do list that definesa task as a name and a description. To model this as an object to be persisted byHibernate into Derby, you create a simple JavaBeans component or POJO thatcontains attributes relating to a task name and a task description.

This class also needs to provide accessor and mutator (in other words, getterand setter) methods for the two major attributes id and date. To do this, create aclass called Task in the same directory as ToDoApplication.java, and eithertype or paste the code in Listing 8 into the directory.

Listing 8. Task.java

package developerworks;

import java.io.Serializable;import java.util.Date;

import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.Temporal;import javax.persistence.TemporalType;

developerWorks® ibm.com/developerWorks

Develop a simple Web application with Apache Wicket and Apache GeronimoPage 14 of 27 © Copyright IBM Corporation 1994, 2008. All rights reserved.

/*** Task type with name and description properties,automatically persisted.*/@Entitypublic class Task implements Serializable {

private Integer id;private String name;private String description;private Date created = new Date();

@Id @GeneratedValue(strategy = GenerationType.AUTO)public Integer getId() {

return id;}public void setId(Integer id) {

this.id = id;}public String getDescription() {

return description;}public void setDescription(String description) {

this.description = description;}public String getName() {

return name;}public void setName(String name) {

this.name = name;}@Temporal(TemporalType.TIMESTAMP)public Date getCreated() {

return created;}protected void setCreated(Date created) {

this.created = created;}

}

As you can probably see, this is just a POJO with nothing special about it, which isone of the great things about Wicket. Because all your models are POJOs, they'reeasily testable and portable. Now that you have the Task class to store tasks, nextyou can create a Wicket Web page for viewing, adding, and deleting tasks.

Create a Wicket Web page

Referring back to Figure 4, the Web page that's going to be created needs to allowyou to show, add, and delete tasks. To do this in Wicket, usually a developer createsa dynamic Web page by extending the Wicket WebPage class. In this case,however, you use some of Databinder's magic to create a DataPage by extendingthe DataPage class, which functions much like Wicket's WebPage class, but letsyou easily work with Hibernate and Wicket via Databinder.

Start by creating a new class called ListAndAdd.java, as shown in Listing 9.

Listing 9. ListAndAdd.java

Listing X: ListAndAdd.javapackage developerworks;

import java.net.URL;

ibm.com/developerWorks developerWorks®

Develop a simple Web application with Apache Wicket and Apache Geronimo© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 15 of 27

import net.databinder.DataRequestCycle;import net.databinder.components.DataForm;import net.databinder.components.DataPage;import net.databinder.components.DateLabel;import net.databinder.components.StyleLink;import net.databinder.components.WebLink;import net.databinder.models.HibernateListModel;import net.databinder.models.SublistProjectionModel;import wicket.Component;import wicket.ResourceReference;import wicket.markup.html.basic.Label;import wicket.markup.html.form.Form;import wicket.markup.html.form.ImageButton;import wicket.markup.html.form.RequiredTextField;import wicket.markup.html.list.ListItem;import wicket.markup.html.list.ListView;import wicket.markup.html.list.PropertyListView;import wicket.model.IModel;import wicket.model.Model;

/*** Single page for adding and deleting bookmarks.*/public class ListAndAdd extends DataPage {

/** Used in DataPage as the page title, and below withinthe page. */

protected String getName() {return "To Do List";

}

/** Adds components to page. */public ListAndAdd() {

super();

// adds the page name as component for on-page displayadd(new Label("pageTitleHeader", new Model() {

public Object getObject(Component component) {return getName();

}}));

// custom styles for this pageadd(new StyleLink("taskStylesheet",

ListAndAdd.class));

// form to hold delete image buttonForm deleteForm = new Form("deleteForm");add(deleteForm);

// data to listIModel listModel = new HibernateListModel("from Task

order by name");// turn list into two vertically ordered columnsfinal IModel sublistModel = new

SublistProjectionModel.Transposed(1, listModel);// view of listdeleteForm.add(new ListView("taskRow", sublistModel) {

protected void populateItem(ListItem parentItem){

parentItem.add(new PropertyListView("task",parentItem.getModel()) {

protected void populateItem(finalListItem item) {

item.setRenderBodyOnly(true);// span tag here would be

invaliditem.add(new Label("name")) ;item.add(new

ImageButton("delete",new

ResourceReference(this.getClass(), "delete_24.png")) {/** Delete from persistent

storage, commit transaction. */

developerWorks® ibm.com/developerWorks

Develop a simple Web application with Apache Wicket and Apache GeronimoPage 16 of 27 © Copyright IBM Corporation 1994, 2008. All rights reserved.

protected void onSubmit() {

DataRequestCycle.getHibernateSession().delete(item.getModelObject());

DataRequestCycle.getHibernateSession().getTransaction().commit();sublistModel.detach();

}});// date the item was added, with

format stringitem.add(new DateLabel("created",

"MMM d k:mm z"));}

});}

});add(new EntryForm("entryForm"));

}

/*** Form for entering new task objects.*/public class EntryForm extends DataForm {

/** Add entry components. */public EntryForm(String id) {

super(id, Task.class); // embeds new Task ina HibernateModel

// inside aBoundCompoundPropertyModel

add(new RequiredTextField("name").setLabel(new Model("Name"))); // Labels

used in error messages

add(new RequiredTextField("description") //required, type validation

.setLabel(new Model("Description")));}/*** Disassociates from its model after submission,

because this form is* for creating new objects only.*/

protected void onSubmit() {super.onSubmit(); // saves to

persistent storage, commits txnclearPersistentObject(); // clears from form

}}

}

Let's look at the code a little more carefully and break down what's going on(although I hope it's fairly intuitive). First, in your constructor you lay out the elementsof the Web page — all of which are going to need a wicket:id in the HTML to tiethem back to the class. For example, Listing 10 shows how to add a page titledynamically to the Web page.

Listing 10. Adding a page title dynamically to the Web page

// adds the page name as component for on-page displayadd(new Label("pageTitleHeader", new Model() {

public Object getObject(Component component) {return getName();

}}));

ibm.com/developerWorks developerWorks®

Develop a simple Web application with Apache Wicket and Apache Geronimo© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 17 of 27

Listing 10 calls the method getName, which returns the string that's your page title.Later, to reference the page title and get it to render in your HTML template, you dosomething like <h1 wicket:id="pageTitleHeader">Some Title</h1>,which tells Wicket when it renders to HTML to actually present this instead: <h1wicket:id="pageTitleHeader">To Do List</h1>.

The same pattern applies for other HTML elements, such as images or even formbuttons. You do something more complex in Listing 11.

Listing 11. Create a custom model of a ListModel from a Hibernate query

IModel listModel = new HibernateListModel("from Taskorder by name");

// turn list into two vertically ordered columnsfinal IModel sublistModel = new

SublistProjectionModel.Transposed(2, listModel);

In Listing 11, you use IModel to create a custom model of a ListModel from theHibernate query from Task order by name. This is passed toSublistProjectionModel to create a sublist with a single column.

This list is then added to the page view and a label for the Task name; a deletebutton, which is represented as an image; and the date in a single task row, shownin Listing 12.

Listing 12. The date in a task row

new ListView("taskRow", sublistModel) {protected void populateItem(ListItem parentItem)

{parentItem.add(new PropertyListView("task",

parentItem.getModel()) {protected void populateItem(final

ListItem item) {item.setRenderBodyOnly(true);

// span tag here would beinvalid

item.add(new Label("name")) ;item.add(new

ImageButton("delete",new ResourceReference(this.getClass(), "delete_24.png")) {

/** Delete from persistentstorage, commit transaction. */

protected void onSubmit() {

DataRequestCycle.getHibernateSession().delete(item.getModelObject());

DataRequestCycle.getHibernateSession().getTransaction().commit();sublistModel.detach();

}}

ListView holds list items — in this case the sublistModel — which can then berepresented in HTML, as shown in Listing 13.

Listing 13. Representing the sublistModel in HTML

developerWorks® ibm.com/developerWorks

Develop a simple Web application with Apache Wicket and Apache GeronimoPage 18 of 27 © Copyright IBM Corporation 1994, 2008. All rights reserved.

<tbody><tr wicket:id="taskRow">

<td><span wicket:id="taskname"><span wicket:id="name">Task 1</span>

</span></td>...

Listing 13 creates a simple HTML table representation of ListView. Finally, onemore item to point out is the use of a nested class, or an inner class, to create aDataForm, like this: public class EntryForm extends DataForm.

Databinder's DataForm class persists your tasks by saving the task model to thedatabase for you. Wicket encourages the use of plain Java object-oriented (OO)techniques to increase code readability, encapsulation, and the logical group ofclasses that's used in one place, just like a normal Java application (as opposed tosomething like a JSP page).

Now that you have an introduction to the Wicket approach to modeling a Web Pagein the Java language, you need to look at how your HTML will look after addingWicket extensions.

The template

Because Wicket templates are written in plain HTML, it's often simple for a designerto mark up what parts of an HTML template need to have Wicket extensions. Mostlikely, this process is an iterative one that occurs between the designer and thedeveloper. However, it's important to note that because there's no specialapplication logic or Java markup in the HTML template, the templating work can bedone in any HTML editor, allowing designers to focus on what they do best —design.

For this tutorial, assume that your designer has provided you with a CSS (shown inListing 14), a simple graphic for a delete button, and an HTML template —ListAndAdd.html — which shares the same name as ListAndAdd.java (seeListing 15).

Listing 14. ListAndAdd.css

li img {vertical-align: middle;border: none;margin-left: .5em;

}

.date {font-style: italic;

}

td {text-align: right;

}

td.taskname {padding-left: 1.5em;

}

ibm.com/developerWorks developerWorks®

Develop a simple Web application with Apache Wicket and Apache Geronimo© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 19 of 27

h { color:#0066FF

}

h1 { font: bold 2.5em "Arial", Sans-Serif; margin: 0;letter-spacing: -1px;

color:#0066FF }h2 { font: bold 2em Arial, Sans-Serif; margin: 0; padding: 0;color:#0066FF}.title { color: #808080; background: #fff; color:#0066FF}

Listing 15 shows the contents of the ListAndAdd.html template.

Listing 15. ListAndAdd.html template

<html><head><wicket:head><!-- add local css, loads directly in WYSIWYG and via Wicketwhen running --><link wicket:id="taskStylesheet" href="ListAndAdd.css"type="text/css"

rel="stylesheet" /></wicket:head><title>Todo List</title></head><body><!-- nothing outside of this extend renders in Wicket --><wicket:extend><h1 wicket:id="pageTitleHeader">Page Title </h1><form wicket:id="entryForm" class="labelAbove">

<div class="row"><label>Name </label><inputwicket:id="name"type="text" style="width: 15em" /></div>

<div class="row"><label>Description </label><inputwicket:id="description" type="text" style="width: 30em"/></div>

<div><input type="submit" value="Add" /></div></form>

<h2>Your List of Tasks</h2><form wicket:id="deleteForm">

<table><tbody>

<tr wicket:id="taskRow"><span wicket:id="task">

<td class="taskname"><span wicket:id="name">Task 1</span>

</td><td><input type="image"

wicket:id="delete" title="Delete this task" src="delete_24.png"onclick="return confirm('Are you sure you want to delete thistask?');" />

</td><td><span class="date" wicket:id="created">Jun

20 9:03EDT</span>

</td></span>

</tr></tbody></table>

</form></wicket:extend></body></html>

The HTML in Listing 15 matches each area where some action or dynamic data

developerWorks® ibm.com/developerWorks

Develop a simple Web application with Apache Wicket and Apache GeronimoPage 20 of 27 © Copyright IBM Corporation 1994, 2008. All rights reserved.

needs to be displayed with a Wicket ID that matches a component inListAndAdd.java. Now your HTML, images, CSS, and any other assets need tobe saved. By default, Wicket wants Web assets to be placed in the same directoryas your Java classes. So save the ListAndAdd.html file into your directory withyour Java classes, as well as the ListAndAdd.css and the delete_24.png.

Note: While many Web applications are made up of only a few HTML templates orviews, some people find Wicket's default behavior of placing Web assets alongsidethe Java code difficult for larger sites. Wicket allows you to control where your Webresources and HTML files are loaded, which you can read more about in several ofthe Wicket Web sites linked to from Resources.

Finally, all that's left to do is package your application as a WAR file and deploy it toGeronimo so you can try out the ToDo application.

Deploy the application to Geronimo

Now that you have everything needed for your Web application ready, you need todeploy it to an application server. The Geronimo server you set up earlier in thetutorial makes deploying the Web application simple.

1. Create a WAR file, which you can do by opening another command shelland navigating to c:\projects\ToDo and either typing or pasting the Mavencommand mvn package. This builds a WAR file for you.

2. To deploy the Web application, make sure Geronimo is started, drag theWAR file from C:\projects\ToDo\target to C:\geronimo\deploy, then go toyour Geronimo server by pointing your browser to http://localhost:8080/and selecting Console.

3. Log in using the default user name system and the default passwordmanager.

4. Check on the applications that have been deployed under Applications >Web App WARs. You should see something like Figure 5.Figure 5. Apache Geronimo installed Web applications

ibm.com/developerWorks developerWorks®

Develop a simple Web application with Apache Wicket and Apache Geronimo© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 21 of 27

From here you can stop, start, restart, or uninstall any of your applications that youhave installed. You can also see the URL for the application. You can either click itor go to http://localhost:8080/ToDo-1.0-SNAPSHOT to see the Web application.

You should now see the ToDo List application shown in Figure 4. Try entering a fewitems to make sure the application works.

Now that you've finished your first simple Wicket Web application, you shouldcontinue to play with Wicket to better learn how the framework operates. Try lettingthe user edit and view a task, or reorder a task by date. Make sure to check outNathan Hamblen's Databinder site (see Resources for a link) for more Databinderexamples. Experiment and make sure to look at the accompanying resources formore useful links for Wicket and Geronimo development.

Section 4. Summary

developerWorks® ibm.com/developerWorks

Develop a simple Web application with Apache Wicket and Apache GeronimoPage 22 of 27 © Copyright IBM Corporation 1994, 2008. All rights reserved.

As you can see, working with Wicket combined with Databinder greatly simplifiesJava development for Web applications. In this tutorial, you looked at how Wicketworks, but it takes some time to master. Wicket is for developers who want a morepure object-oriented WAR file to build Web applications. Make sure to check out theWicket home page (see Resources) and the tutorials there to get a betterunderstanding of how Wicket works.

You also saw how Geronimo provides a unified Java EE application server, a Webserver, and an embedded database, which simplifies setting up and deploying aJava Web application. Wicket combined with Geronimo lets you develop rich,scalable, and 100% open source Web applications in record time, without thecomplexity, cost, or sometimes frustrating management incurred in more traditionalframeworks and application servers.

ibm.com/developerWorks developerWorks®

Develop a simple Web application with Apache Wicket and Apache Geronimo© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 23 of 27

Downloads

Description Name Size Download method

Tutorial source code ToDo.zip 459KB HTTP

Information about download methods

developerWorks® ibm.com/developerWorks

Develop a simple Web application with Apache Wicket and Apache GeronimoPage 24 of 27 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Resources

Learn

• Deployment plans are the Geronimo version of the J2EE deploymentdescriptors. Access Geronimo deployment plans from Apache.org.

• Read "Create, deploy, and debug Apache Geronimo applications"(developerWorks, May 2005) to learn how to use the Eclipse plug-in to developand deploy Web applications to the Apache Geronimo server.

• Read Control where HTML files are loaded from from the Apache Wicketdocumentation.

• Check out the Wicket home page and the tutorials there to get a betterunderstanding of how Wicket works.

• Visit Wicket Examples for a selection of examples that best demonstrate itscore functionality.

• Read a solid article, "Introduction to Apache Maven 2" (developerWorks,December 2006).

• Read the developerWorks tutorial series J2EE Web services in Geronimo tolearn about incorporating Web services into a J2EE-based application deployedon the Apache Geronimo application server.

• Read Aaron Mulder's online book, Apache Geronimo Development andDeployment , about installing and configuring the Apache Geronimo applicationserver.

• See the Geronimo Wiki for additional Geronimo documentation, includinginstallation information.

• Read about plug-ins and other cutting-edge features in Geronimo 1.1 in thearticle "The Geronimo renegade: The Apache Geronimo of the future"(developerWorks, June 2006).

• Get detailed information about deploying your application to Geronimo in thearticle "Deploy J2EE applications on Apache Geronimo" (developerWorks,January 2006).

• Check out upcoming conferences, trade shows, webcasts, and other eventsaround the world that are of interest to IBM® open source developers.

• Read what Nathan Hamblen has to say about Databinder, a lightweight utility hewrote that lets Wicket and Hibernate work together extremely well, greatlysimplifying development of data-driven Wicket applications.

• Check out the developerWorks Apache Geronimo project area for articles,tutorials, and other resources to help you get started developing with Geronimotoday.

• Find helpful resources for beginners and experienced users at the Get startednow with Apache Geronimo section of developerWorks.

ibm.com/developerWorks developerWorks®

Develop a simple Web application with Apache Wicket and Apache Geronimo© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 25 of 27

• Check out the IBM Support for Apache Geronimo offering, which lets youdevelop Geronimo applications backed by world-class IBM support.

• Visit the developerWorks Open source zone for extensive how-to information,tools, and project updates to help you develop with open source technologiesand use them with IBM's products.

• Stay current with developerWorks technical events and webcasts.

• Browse all the Apache articles and free Apache tutorials available in thedeveloperWorks Open source zone.

• Browse for books on these and other technical topics at the Safari bookstore.

Get products and technologies

• Get Apache Wicket (Wicket is not in an incubation period with Apache).

• Get Databinder, a Java programming toolkit for data-driven Web applicationsbased on Wicket.

• Download Qwicket, a quick-start application for the Wicket framework.

• Get the Wicket Bench, an Eclipse plug-in for Wicket.

• Download Maven 2.0.7.

• Download the latest version of Apache Geronimo.

• Download your free copy of IBM WebSphere® Application Server CommunityEdition -- a lightweight J2EE application server built on Apache Geronimo opensource technology that is designed to help you accelerate your developmentand deployment efforts.

• Innovate your next open source development project with IBM trial software,available for download or on DVD.

Discuss

• Participate in the discussion forum for this content.

• Stay up to date on Geronimo developments at the Apache Geronimo blog.

• Get involved in the developerWorks community by participating indeveloperWorks blogs.

About the author

Robi SenRobi Sen is the vice president of services for Department 13, LLC, an IT consultancy,where he spends most of his time helping customers, ranging from Fortune 500companies to startups, define and manage their technology challenges. He haswritten widely on different technologies and often lectures and presents at variousconventions.

developerWorks® ibm.com/developerWorks

Develop a simple Web application with Apache Wicket and Apache GeronimoPage 26 of 27 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Trademarks

IBM, the IBM logo, and WebSphere are registered trademarks of IBM in the UnitedStates, other countries or both.Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc., in theUnited States, other countries, or both.Microsoft and Windows are trademarks of Microsoft Corporation in the United States,other countries, or both.Linux is a registered trademark of Linus Torvalds in the United States, othercountries, or both.

ibm.com/developerWorks developerWorks®

Develop a simple Web application with Apache Wicket and Apache Geronimo© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 27 of 27