Author: Cloves Carneiro
Translator: simmone
Copyright Statement: Any website authorized by Matrix, whenreprinting, please be sure to indicate the original source and author information of the article and this statement in the form of a hyperlink. Author: Cloves Carneiro;simmone
Original address: http://www.javaworld.com/javaworld/jw-06-2005/jw-0620-dwr.html
Chinese address: http://www.matrix.org.cn/resource/article/43/43926_DWR_AJAX.html
Keywords: DWR javascript :void(0);">AJAX
Overview
This article explains the use of theopen source project DWR (Direct Web Remoting) and the concept of javascript :void(0);">AJAX (Asynchronous JavaScript and XML ) to improve the usability of web applications. The author shows step by step how DWR makes javascript :void(0);">AJAX application is simple and fast. (1,600 words; June 20, 2005)
javascript :void(0);">AJAX, or Asynchronous JavaScript and XML, describes a developmenttechnology that uses a mixture of HTML (or XHTML) and cascading style sheets to express information to create interactive Web applications; The DocumentObject Model (DOM), JavaScript, dynamically displays and interacts with expressed information; and, the XMLHttpRequest object exchanges and processes data asynchronously with the Web server.
Many examples on the Internet demonstrate the necessary steps to interact with the server using XMLHttpRequest inside an HTML file. When writing and maintaining XMLHttpRequest code manually, developers must deal with many potential issues, especially issues like cross-browser DOM implementation compatibility. This will lead to spending countless hours coding and debugging Javascript code, which is obviously not friendly to developers.
The DWR (Direct Web Remoting) project is an open source solution under the Apache license for developers who want to use javascript :void(0);">AJAX and XMLHttpRequest in a simple way. It has A set of Javascript functions that simplifythe method of calling Java objects on the application server from HTML pages. It manipulates different types of parameters while maintaining the readability of the HTML code.
DWR is not an insertion into a design, nor does it force objects to use any kind of inheritance structure. It works well with applications within the servlet framework. For developers who lack DHTML programming experience, DWR also provides a JavaScript library that contains frequently used DHTML tasks, such as assembling tables, filling select drop-down boxes with items, and changing the content of HTML elements such as <div> and <span. >
The DWR website is thorough and has extensive documentation, which is the basis for this article. Some examples are provided to show how DWR is used and what kind ofwork can be accomplished with its libraries.
This article allows readers to see how a web application using DWR is built step by step. I'll show you the necessary details to create this simple sample application, which is downloadable and can be deployed in your environment to see how DWR works.
NOTE: It is not difficult to find information about javascript :void(0);">AJAX; there are several articles and blog entries on the web covering this topic, each trying to point out and comment on a different aspect of the concept. In In the resources section you will find some interesting links to examples and articles to learn more about javascript :void(0);">AJAX.
Sample Application <BR>The sample application used in this article simulates an apartment rental search engine in Toronto. Users can select a set of search criteria before searching. In order to improve interactivity, javascript :void(0);">AJAX is used in the following two situations:
·The application informs the user how many search results will be returned based on his selections. This number is updated in real time - using javascript :void(0);">AJAX - when the number of bedrooms and bathrooms selected by the user, or the price range changes. When there are no or too many search results matching the criteria, the user does not have to Click the search button.
· The database query and retrieval of results is done by javascript :void(0);">AJAX. When the user presses the show results button, the database performs the search. In this way, the application looks more responsive, and the entire page does not need to Overloaded to display results.
Database <BR>The database we use is HSQL, which is a Java SQL database engine that takes up very little resources and can be bundled with Web applications withoutinstallation and configuration. A SQL file is used to create an in-memory table and add some records when the web application context starts.
The Java class <BR>application contains two main classes called Apartment and ApartmentDAO. The Apartment.java class is a simple Java class with properties and getter/setter methods. ApartmentDAO.java is the data access class used to query the database and return information based on the user's search criteria. The implementation of the ApartmentDAO class is straightforward; it uses Java database connection calls directly to get the total number of apartments and the list of available apartments that match the user's request.
DWR configuration and use <BR>Setting up the use of DWR is simple: copy the DWR jar file into the WEB-INF/lib directory of the web application, add a servlet declaration in web.xml, and create the DWR configuration file. A separate jar file is required for the distribution of DWR. You must add the DWR servlet to the deployment descriptor section in your application's WEB-INF/web.xml.
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<display-name>DWR Servlet</display-name>
<description>Direct Web Remoter Servlet</description>
<servlet-class>uk.ltd.getahead.dwr.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>
An optional step is to set DWR to debug mode - as in the example above - by setting the debug parameter to true in the servlet description section. When DWR is in debug mode, you can see all accessible Java objects from the HTML page. A web page containing a list of available objects will appear at the URL /WEBAPP/dwr, which displays the public methods of the object. The methods listed can be called from the page, allowing you, for the first time, to run methods on objects on the server. The following image shows what the debug page looks like:
Debug page
Now you have to let DWR know what object will receive the request via the XMLHttpRequest object. This task is accomplished by a configuration file called dwr.xml. In the configuration file, you define the objects that DWR allows you to call from the web page. By design, DWR allows access to all public methods of a published class, but in our case we only allow access to a few methods. Here is the configuration file for our example:
<dwr>
<allow>
<convert converter="bean" match="dwr.sample.Apartment"/>
<create creator="new" javascript="ApartmentDAO" class="dwr.sample.ApartmentDAO">
<include method="findApartments"/>
<include method="countApartments"/>
</create>
</allow>
</dwr>
The above file achieves both goals in our example. First, the <convert> tag tells DWR to convert the type of the dwr.sample.Apartment object to an associative array, because, for security reasons, DWR does not convert ordinary beans by default. Second, the <create> tag lets DWR expose the dwr.sample.ApartmentDAO class for JavaScript calls; the JavaScript files we use in the page are defined by the javascript attribute. We must pay attention to the <include> tag, which specifies which methods of the dwr.sample.ApartmentDAO class are available.
After the HTML/JSP code <BR>is configured, you can start your Web application. At this time, DWR will be ready to call the required methods from your HTML or Java server-side page (JSP). There is no need to You create JavaScript files. In the search.jsp file, we must add the JavaScript interface provided by DWR, as well as the DWR engine, and add the following three lines to ourcode :
<script src='dwr/interface/ApartmentDAO.js'></script>
<script src='dwr/engine.js'></script>
<script src='dwr/util.js'></script>
We noticed that when the user changes the search criteria, this is the first application of javascript :void(0);">AJAX in the sample program; as he sees , the number of available apartments is updated when the criteria changes. I created two JavaScript functions: The ApartmentDAO.countApartments() function is the most interesting part. is the first parameter, the loadTotal() function, which specifies the JavaScript method that DWR will call when receiving a response from the server. loadTotal is then called to display the results in the <div> of the HTML page. JavaScript functions used in interactive scenarios:
function updateTotal() {
$("resultTable").style.display = 'none';
var bedrooms = document.getElementById("bedrooms").value;
var bathrooms = document.getElementById("bathrooms").value;
var price = document.getElementById("price").value;
ApartmentDAO.countApartments(loadTotal, bedrooms, bathrooms, price);
}
function loadTotal(data) {
document.getElementById("totalRecords").innerHTML = data;
}
Obviously, the user wants to see apartment listings that match his search criteria. Then, when the user is satisfied with his search criteria and the totals are valid, he presses the button that displays the results, which calls the updateResults() JavaScript method:
function updateResults() {
DWRUtil.removeAllRows("apartmentsbody");
var bedrooms = document.getElementById("bedrooms").value;
var bathrooms = document.getElementById("bathrooms").value;
var price = document.getElementById("price").value;
ApartmentDAO.findApartments(fillTable, bedrooms, bathrooms, price);
$("resultTable").style.display = '';
}
function fillTable(apartment) {
DWRUtil.addRows("apartmentsbody", apartment, [ getId, getAddress, getBedrooms, getBathrooms, getPrice ]);
}
The updateResults() method clears the table field that stores search returned results, obtains the required parameters from the user interface, and passes these parameters to the ApartmentDAO object created by DWR. Then the database query will be executed and fillTable() will be called, which parses the object returned by DWR (apartments) and displays it into the page (apartmentsbody).
Security Factors <BR>To keep the example brief, the ApartmentDAO class is kept as simple as possible, but such a class usually has a set of set methods to manipulate data, such as insert(), update() and delete(). DWR exposes all public methods to be called by all HTML pages. For security reasons, it is unwise to expose your data access layer like this. Developers can create a facade that centralizes communication between all JavaScript functions and underlying business components, thus limiting excessive exposure of functionality.
Conclusion <BR>This article is just a beginning for you to use DWR-powered javascript :void(0);">AJAX in your projects. DWR allows you to focus on how to improve the interaction model of your application. , eliminating the burden of writing and debugging JavaScript code. The most interesting challenge with javascript :void(0);">AJAX is defining where and how to improve usability. DWR is responsible for operating the communication between the Web page and your Java objects, thus helping you to focus entirely on how to make your application's user interface more friendly.
I would like to thank Mircea Oancea and Marcos Pereira, who read this article and gave very valuable feedback.
Resources ·javaworld.com:javaworld.com
·Matrix-Java developer community: http://www.matrix.org.cn/
·onjava.com:onjava.com
·Download all source code of the sample program: http://www.javaworld.com/javaworld/jw-06-2005/dwr/jw-0620-dwr.war
·DWR: http://www.getahead.ltd.uk/dwr/index.html
·HSQL: http://hsqldb.sourceforge.net/
·javascript :void(0);">Definition of AJAX: http://en.wikipedia.org/wiki/javascript :void(0);">AJAX
· "javascript :void(0);">AJAX: A New Path to Web Applications": Jesse James Garrett (Adaptive Path, 2005.2): http://www.adaptivepath.com/publications/essays/archives/000385. php
· “A very dynamic web interface” Drew McLellan (xml.com, 2005.2): http://www.xml.com/pub/a/2005/02/09/xml-http-request.html
·XMLHttpRequest & javascript :void(0);">AJAX working example: http://www.fiftyfoureleven.com/resources/programming/xmlhttprequest/examples
· “Usable XMLHttpRequest Practices” Thomas Baekdal (Baekdal.com, 2005.3): http://www.baekdal.com/articles/Usability/usable-XMLHttpRequest/
·"XMLHttpRequest Usage Guidelines" Thomas Baekdal (Baekdal.com, 2005.2): http://www.baekdal.com/articles/Usability/XMLHttpRequest-guidelines/