DWR Java AJAX Applications

December 13, 2008

AJAX

In this chapter, we will get to the actual hands-on work. We will develop samples based on DWR, which show how to dynamically change the common user interface elements such as tables and lists as well as fi eld completion. We also make a dynamic user interface skeleton for our samples that will hold all the samples in this book.

The section on dynamic user interfaces shows how to get started with a DWR application, and it presents a user interface skeleton that will be used to hold the tables and lists sample, and the fi eld completion (aka. autosuggest/autocomplete) sample. Samples in the following chapter will use the same user interface skeleton, with the exception of the sample applications in Chapter 7.

The following are the sections in this chapter:

  • Creating a Dynamic User Interface—starts with creating a web project and a
    basis for samples mentioned in this chapter
  • Implementing Tables and Lists—shows us how to use DWR with them
  • Implementing Field Completion—has a sample for typical fi eld completion

Creating a Dynamic User Interface

The idea behind a dynamic user interface is to have a common “framework” for all samples. We will create a new web application and then add new features to the application as we go on. The user interface will look something like the following figure:

The user interface has three main areas: the title/logo that is static, the tabs that are dynamic, and the content area that shows the actual content.

The idea behind this implementation is to use DWR functionality to generate tabs and to get content for the tab pages. The tabbed user interface is created using a CSS template from the Dynamic Drive CSS Library (http://dynamicdrive.com/style/csslibrary/item/css-tabs-menu). Tabs are read from a properties fi le, so it is possible to dynamically add new tabs to the web page. The following screenshot shows the user interface.

dwr-1

Creating a New Web Project

  • 1.First, we will create a new web project. Using the Eclipse IDE we do the following: select the menu File | New | Dynamic Web Project.
  • 2.This opens the New Dynamic Web Project dialog; enter the project name DWREasyAjax and click Next, and accept the defaults on all the pages till the last page, where Geronimo Deployment Plan is created as shown in the following screenshot:
  • dwr-2
  • 3.Enter easyajax as Group Id and DWREasyAjax as Artifact Id. On clicking Finish, Eclipse creates a new web project. The following screen shot shows the generated project and the directory hierarchy.
  • dwr-3
  • 4.Before starting to do anything else, we need to copy DWR to our web application. All DWR functionality is present in the dwr.jar fi le, and we just copy that to the WEB-INF | lib directory.

A couple of files are noteworthy: web.xml and geronimo-web.xml. The latter is generated for the Geronimo application server, and we can leave it as it is. Eclipse has an editor to show the contents of geronimo-web.xml when we double-clickthe file.

dwr-4

Configuring the Web Application

The context root is worth noting (visible in the screenshot above). We will need it when we test the application.

The other XML fi le, web.xml, is very important as we all know. This XML will hold the DWR servlet defi nition and other possible initialization parameters. The following code shows the full contents of the web.xml file that we will use:

<?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><b><i>DWR</i></b>EasyAjax</display-name>
<servlet>
<display-name><b><i>DWR</i></b> Servlet</display-name>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>
org.directwebremoting.servlet.DwrServlet
</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

We hav e already seen the servlet defi nition in Chapter 3, in the section on confi guration. We use the same debug-init parameter here. Servlet mapping is the commonly used /dwr/*.

We remember that DWR cannot function without the dwr.xml configuration file. So we need to create the confi guration fi le. We use Eclipse to create a new XML file in the WEB-INF directory. The following is required for the user interface skeleton. It already includes the allow-element for our DWR based menu.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dwr PUBLIC
"-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN"
"http://getahead.org/dwr/dwr20.dtd">
<dwr>
<allow>
<create creator="new" javascript="HorizontalMenu">
<param name="class" value="samples.HorizontalMenu" />
</create>
</allow>
</dwr>

In the allow element, there is a creator for the horizontal menu Java class that we are going to implement here. The creator that we use here is the new creator, which means that DWR will use an empty constructor to create Java objects for clients. The parameter named class holds the fully qualifi ed class name.

Developing the Web Application

Since we have already defi ned the name of the Java class that will be used for creating the menu, the next thing we do is implement it. The idea behind the HorizontalMenu class is that it is used to read a properties fi le that holds the menus that are going to be on the web page.

We add properties to a fi le named dwrapplication.properties, and we create it in the same samples-package as the HorizontalMenu-class. The properties fi le for the menu items is as follows:

menu.1=Tables and lists,TablesAndLists
menu.2=Field completion,FieldCompletion

The syntax for the menu property is that it contains two elements separated by a comma. The fi rst element is the name of the menu item. This is visible to user. The second is the name of HTML template fi le that will hold the page content of the menu item. The class contains just one method, which is used from JavaScript and via DWR to retrieve the menu items. The full class implementation is shown here:

package samples;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
public class HorizontalMenu {
public HorizontalMenu() {
}
public List<String> getMenuItems() throws IOException {
List<String> menuItems = new Vector<String>();
InputStream is = this.getClass().getClassLoader().
getResourceAsStream(
"samples/dwrapplication.properties");
Properties appProps = new Properties();
appProps.load(is);
is.close();
for (int menuCount = 1; true; menuCount++) {
String menuItem = appProps.getProperty("menu." + menuCount);
if (menuItem == null) {
break;
}
menuItems.add(menuItem);
}
return menuItems;
}
}

The implementation is straightforward. The getMenuItems() method loads properties using the ClassLoader.getResourceAsStream() method, which searches the class path for the specified resource. Then, after loading properties, a for loop is used to loop through menu items and then a List of String-objects is returned to the client. The client is the JavaScript callback function that we will see later. DWR automatically converts the List of String objects to JavaScript arrays, so we don’t have to worry about that.

Testing the Web Application

We hav en’t completed any client-side code now, but let’s test the code anyway. Testing uses the Geronimo test environment.

1.The Project context menu has the Run As menu that we use to test the application as shown in the following screenshot:

dwr-5

2.Run on Server opens a wizard to defi ne a new server runtime. The following screenshot shows that the Geronimo test environment has already been set up, and we just click Finish to run the application. If the test environment is not set up, we can manually defi ne a new one in this dialog:

dwr-6

3.After we click Finish, Eclipse starts the Geronimo test environment and our application with it. When the server starts, the Console tab in Eclipse informs us that it’s been started.

dwr-7

The Servers tab shows that the server is started and all the code has been synchronized, that is, the code is the most recent (Synchronization happens whenever we save changes on some deployed fi le.) The Servers tab also has a list of deployed applications under the server. Just the one application that we are testing here is visible in the Servers tab.

dwr-8

Now comes the interesting part—what are we going to test if we haven’t really implemented anything? If we take a look at the web.xml fi le, we will fi nd that we have defi ned one initialization parameter. The Debug parameter is true, which means that DWR generates test pages for our remoted Java classes. We just point the browser (Firefox in our case) to the URL  ttp://127.0.0.1:8080/DWREasyAjax/
dwr and the following page opens up:

dwr-9

This page w ill show a list of all the classes that we allow to be remoted. When we click the class name, a test page opens as in the following screenshot:

dwr-10

This is an interesting page. We see all the allowed methods, in this case, all public class methods since we didn’t specifi cally include or exclude anything. The most important ones are the script elements, which we need to include in our HTML pages. DWR does not automatically know what we want in our web pages, so we must add the script includes in each page where we are using DWR and a
remoted functionality.

Then there is the possibility of testing remoted methods. When we test our own method, getMenuItems(), we see a response in an alert box:

dwr-11

The array in the alert box in the screenshot is the JavaScript array that DWR returns from our method.

Developing Web Pages

The next step is to add the web pages. Note that we can leave the test environment running. Whenever we change the application code, it is automatically published to test the environment, so we don’t need to stop and start the server each time we make some changes and want to test the application.

The CSS style sheet is from the Dynamic Drive CSS Library. The fi le is named styles.css, and it is in the WebContent directory in Eclipse IDE. The CSS code is as shown:

/*URL: http://www.dynamicdrive.com/style/ */
.basictab{
padding: 3px 0;
margin-left: 0;
font: bold 12px Verdana;
border-bottom: 1px solid gray;
list-style-type: none;
text-align: left; /*set to left, center, or right to align the menu as
desired*/
}
.basictab li{
display: inline;
margin: 0;
}
.basictab li a{
text-decoration: none;
padding: 3px 7px;
margin-right: 3px;
border: 1px solid gray;
border-bottom: none;
background-color: #f6ffd5;
color: #2d2b2b;
}
.basictab li a:visited{
color: #2d2b2b;
}
.basictab li a:hover{
background-color: #DBFF6C;
color: black;
}
.basictab li a:active{
color: black;
}
.basictab li.selected a{ /*selected tab effect*/
position: relative;
top: 1px;
padding-top: 4px;
background-color: #DBFF6C;
color: black;
}

This CSS is shown for the sake of completion, and we will not go into details of CSS style sheets. It is suffi cient to say that CSS provides an excellent method to create websites with good presentation.

The next step is the actual web page. We create an index.jsp page, in the WebContent directory, which will have the menu and also the JavaScript functions for our samples. It should be noted that although all JavaScript code is added to a single JSP page here in this sample, in “real” projects it would probably be more useful to create a separate fi le for JavaScript functions and include the JavaScript fi le in the HTML/JSP page using a code snippet such as this:

email

Comments

comments