The examples shown in this article require you to have Eclipse installed, as well as a Web application server. The examples specifically use Tomcat 6.0, but other Web application servers such as WebSphere® Application Server Community Edition, Jetty, or older versions of Tomcat should also work. If you don't have a Web application server installed, see Resources to download and install Apache Tomcat 6.0 or WebSphere Application Server Community Edition.
Apache Click is a Web application framework that lets you quickly build Java Web applications. The purpose of Apache Click is to provide a method of building Web applications without using JSPs or MVC frameworks, which can be heavy-handed for some Web applications. Apache Click is licensed with the Apache License (see Resources).
Instead of a heavy framework, Apache Click uses HTML templates and plain old Java objects (POJOs). The HTML templates are processed by the Apache Velocity template engine (see Resources to learn more about Apache Velocity), which aims to make the templates as close to standard HTML as possible without requiring special tags. Velocity templates do not require a steep learning curve for syntax and allow Web developers to leverage existing HTML skills.
The POJOs inherit from base classes provided by the Apache Click
distribution. Apache Click includes a Page and
component classes that you write subclasses for to implement the code that
does the processing for each page. These components provide out-of-the-box
functions that let you build HTML controls and respond to events.
Apache Click also includes an API for mock testing, which allows better unit testing, continuous integration builds, and test-driven development (TDD). See Resources to learn more about the Mock API.
Apache Click components and event handling
The org.apache.click.Page class is the base
class for each page component. The Page base
class contains methods that allow you to handle events when the page is
initialized (onInit()), rendered
(onRender()), and for page security
(onSecurityCheck()). In your classes that
extend Page, you can override these methods to
provide custom functions. Each class that extends
Page might also contain methods that handle
events on the page.
You can create stateful pages by implementing the
java.io.Serializable interface and calling the
Page base class's
setStateful() method in the constructor (see
Listing 1).
Listing 1. Setting the stateful property in the constructor
public WelcomePage() {
setStateful(true);
} |
Apache Click comes with several control components that correspond to HTML elements. These control components let you programmatically set up forms by dynamically adding controls. Using these controls, you can get and set the HTML control data programmatically in your Java code.
Using the setEventListener() method of field
controls (that is, TextField,
Select), you can define a method on your
extended Page class that executes during the
form processing, if the input in the field is valid.
Buttons and links also provide event handling. You can create a new submit
button on a form and link the button to a method on your
Page class using the declaration shown in
Listing 2.
Listing 2. Creating a submit button with the
onClick event handler
Submit submitButton = new Submit("Submit Me", this, "onClick"); |
When the button is clicked, the event is dispatched to your custom
Page class's
onClick() method. Any code that is in the
onClick() method is executed, including code to
save the data to a database or to forward to a new page.
To read more about the API, see Resources.
By default, Apache Click uses the Apache Velocity templating engine. The
templates are matched automatically with the classes that extend
Page in your application using some default
mapping rules. For instance, a page class called
HelloPage automatically maps to the HTML file
called hello.html in your Web project. A page called
HelloWorldPage automatically maps to a page
called helloWorld.html or hello-world.html.
If you don't like the default page mapping, you can change it by modifying the click.xml file to add your own custom mapping.
Along with the page mapping that Velocity uses, you can decide not to use Velocity as your templating engine. Apache Click lets you use JSPs for rendering, which may help you use existing JSPs.
Download Apache Click from the Web site (see Resources). After downloading it, extract the compressed (.zip) file to a location that is easy for you to remember.
If you want to see the examples that come with Apache Click, you can deploy the click-examples.war file from the dist folder to your Web application server. The examples include many different scenarios, such as building tables, using different controls, and using different templates.
After you download and extract the files, you are ready to create a Web application that includes the Apache Click libraries.
Install Apache Click by putting the required Java Archive (JAR) files in your Web project. After including it in your Web project, deploy your project to your Web application server.
To create a Web application that uses Apache Click using Eclipse, follow these steps:
- Select New > Other from the Eclipse menu.
- From Select a Wizard, choose Web / Dynamic Web Project and click Next.
- Type a name for Project Name (for example,
MyFirstClick). - Select a Target Runtime, such as Apache Tomcat 6.0. See Resources to learn more about configuring run times for Eclipse.
- Click Finish—you can leave the default values for the remaining fields.
After completing these steps, you should have a new empty Web project in Eclipse (see Figure 1).
Figure 1. The empty Web project
Now you can import the Apache Click libraries. Use the following steps to import the libraries:
- Click File > Import.
- Select General / File System from the list and click Next.
- Browse to the directory in which you expanded the Apache Click files and select the dist directory.
- From the list of files, select the click-{version}.jar and
click-{version}-extras.jar files (see Figure 2).
Figure 2. Importing the JAR files
- Make sure the WebContent/WEB-INF/lib folder is selected in the Into folder field before clicking Finish.
Now that you have the JAR files in your WEB-INF directory, modify the Web
application's web.xml file to include the
ClickServlet, which is the single servlet used
by Apache Click to dispatch events. After you configure this servlet, you
won't need to modify the web.xml file any more to use the examples shown
in this article. The web.xml contents are shown in
Listing 3.
Listing 3. The web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>MyFirstClick</display-name>
<servlet>
<servlet-name>ClickServlet</servlet-name>
<servlet-class>org.apache.click.ClickServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ClickServlet</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>welcome.html</welcome-file>
</welcome-file-list>
</web-app> |
Now create a package into which your page classes will go (for example,
com.example.myfirstclick.pages). After you
create the package, create a new file called click.xml in your Web
project's WEB-INF folder. Put the name of the package you just created in
the click.xml file, as shown in Listing 4.
Listing 4. The click.xml file
<?xml version="1.0" encoding="UTF-8"?>
<click-app>
<pages package="com.example.myfirstclick.pages" />
</click-app> |
Now that your project is set up, you are ready to start writing classes
that extend the Apache Click classes. Your first class extends from
Page, which is the base class for all of your
page components. Create the new class in the package you created by
selecting File > New > Other and selecting Java /
Class. Make sure to enter
org.apache.click.Page as the Superclass.
Add the contents shown in Listing 5 into your new class.
Listing 5. The
WelcomePage class
package com.example.myfirstclick.pages;
import org.apache.click.Page;
public class WelcomePage extends Page {
// Initialize the value to something
protected String theMessage = "Welcome!";
public WelcomePage() {
// Add the value to the map ("message" = "$message")
addModel("message", theMessage);
}
} |
Now that you've created the WelcomePage class,
you need to create an HTML page that is the template for the output for
the browser. Because the default template engine for Apache Click is
Apache Velocity, the HTML file will be similar to a normal, static HTML
page.
Create the new HTML page—called welcome.html—in the WebContent folder of your Web project and add the content as shown in Listing 6.
Listing 6. The welcome.html file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>MyFirstClick Welcome</title>
</head>
<body>
<p>$message</p>
</body>
</html> |
Notice the $message variable in the new HTML
file. This is a variable that is replaced by the Velocity template engine
when the page is generated. The ClickServlet
matches the WelcomePage class with the
welcome.html file. The WelcomePage class
initializes its message field to a value
(Welcome), then, in the constructor, adds it to
the model using the addModel() method passing
the name of the variable (message maps to
$message) and the value (the
theMessage field). The value assigned to the
field is displayed in the browser.
Running the sample application
Now that you've created the files, you can try the application by exporting the files as a Web Archive (WAR) to the Tomcat webapps folder. The easiest way to do this is to follow these steps using Eclipse:
- Click on the project and select File > Export.
- Select Web / WAR file and click Next.
- In the Destination field, browse to the Tomcat webapps folder.
- Make sure Overwrite existing files is selected and click
Finish (see Figure 3).
Figure 3. Exporting the project as a WAR
After you export the WAR file to the Tomcat webapps directory, you can browse to your new page by pointing your browser to http://localhost:8080/MyFirstClick/welcome.html (the URL may vary if your Web application server is bound to a different port or if you choose a different name for your Web application).
Experiment with this sample by modifying the value of the message field on
the WelcomePage, then redeploy it to the Web
application server. When you see the value change, you are ready for a
more dynamic example.
Now that you've done a simple welcome page, you are ready to do something a little more complicated. Few dynamic Web sites consist of only read-only data—most of them require user input at some point and do something with that user input. A typical example is a form that accepts input and then shows the user a different Web page with the input displayed.
To view this example, create another class that extends
Page. Name this new class
InputPage (see
Listing 7).
Listing 7. The
InputPage class
package com.example.myfirstclick.pages;
import org.apache.click.Page;
import org.apache.click.control.Form;
import org.apache.click.control.Submit;
import org.apache.click.control.TextField;
public class InputPage extends Page {
public Form form = new Form();
private TextField nameField;
public InputPage() {
form.setLabelsPosition(Form.POSITION_TOP);
nameField = new TextField("Enter your name");
form.add(nameField);
form.add(new Submit("Submit", this, "onSubmitClick"));
}
public boolean onSubmitClick()
{
SayHelloPage nextPage = (SayHelloPage)getContext().createPage("/sayHello.html");
nextPage.setName(nameField.getValue());
setForward(nextPage);
return false;
}
} |
The new class sets up a Form object in the
constructor and adds a field to it for input. Then the class adds an HTML
submit button with a handler (the
onSubmitClick() method). The handler executes
when the submit button is pressed, so in the handler the class should set
up the next page. Until you add the next page (that is,
SayHelloPage), the code will not compile.
Now create a new HTML file and name it input.html in the WebContent folder
of your Web project. Put a $form variable on
the page, which will be substituted with the HTML output from the form
field on the InputPage class. When you're done,
the input.html file should look like Listing 8.
Listing 8. The input.html file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>MyFirstClick Input Sample</title>
</head>
<body>
$form
</body>
</html> |
Now add the page that displays the input as another class called
SayHelloPage, making sure it also extends from
org.apache.click.Page. The new class should
look like that in Listing 9.
Listing 9. The
SayHelloPage class
package com.example.myfirstclick.pages;
import org.apache.click.Page;
public class SayHelloPage extends Page {
private String name;
@Override
public void onInit()
{
super.onInit();
if (name != null)
{
addModel("name", name);
}
}
public void setName(String name) {
this.name = name;
}
} |
This class overrides the Page base class's
onInit() method to set up the values that are
displayed on the page. Remember to add checks for null to any value that
you add to the model with the addModel()
method—if you try to add a null value, it throws an
IllegalArgumentException. This forces you to
make sure you write code that displays the page properly if values are
null.
The name field in the SayHelloPage is exposed
with a public getter, setName(). This accessor
is called back in the onSubmitClick() event
handler method in the InputPage after it gets a
new instance of the page.
The onSubmitClick() method sets the name using
the value from the nameField control
(nameField.getValue()). Then it forwards to the
page using the setForward() method. The result
is that the name field on the SayHelloPage is
populated with the value from the input box and put in
$name.
Now add an HTML file, called sayHello.html, that contains the
$name variable. The contents of sayHello.html
are shown in Listing 10.
Listing 10. The sayHello.html page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Results</title>
</head>
<body>
<p>Hello, $name!</p>
</body>
</html> |
To run this example, point your Web browser to http://localhost:8080/MyFirstClick/input.html. Enter a value in the text box, and press Submit. Your value now displays in the browser.
Using Apache Click, you can quickly write Web applications using a lightweight model free of heavy frameworks. The simplicity of Apache Click enables you to use your own object-oriented programming practices and patterns. The default templating engine, Velocity, allows the HTML code to remain truer to HTML specifications by not requiring custom tags.
The component and event model in Apache Click provides a method of building HTML controls and handling events that has a low learning curve.
Learn
- Read about the
Apache License.
- Read more about
Apache Velocity.
- Learn more about the
Apache Click Mock API.
- Learn more about the
Apache Click API.
- Read
"Developing Web applications with Tomcat and Eclipse"
(developerWorks, May 2007) to learn more about using Apache Tomcat with
Eclipse to build Web applications.
- Browse the
technology bookstore
for books on these and other technical topics.
Get products and technologies
- Download Apache
Tomcat.
- Download Apache
Click .
- Download
WebSphere
Application Server Community Edition,
a lightweight Java EE application server built on Apache Geronimo
technology.
- Download
IBM product evaluation versions
or
explore
the online trials in the IBM SOA Sandbox
and get your hands on application development tools and middleware
products from DB2®, Lotus®, Rational®, Tivoli®,
and WebSphere.
Discuss
- Check out
developerWorks
blogs
and get involved in the
developerWorks community.

Nathan A. Good lives in the Twin Cities area of Minnesota. Professionally, he does software development, software architecture, and systems administration. When he's not writing software, he enjoys building PCs and servers, reading about and working with new technologies, and trying to get his friends to make the move to open source software. He's written and co-written many books and articles, including Professional Red Hat Enterprise Linux 3, Regular Expression Recipes: A Problem-Solution Approach and Foundations of PEAR: Rapid PHP Development.




