DWR makes Ajax so simple

Source: Internet
Author: User
Tags add define object functions html page sql object model access
Ajax Use DWR to start using javascript:void (0) in your Web application; >ajax
Author: Cloves Carneiro
Translator: Simmone

Copyright notice: Any access to the matrix authorized website, reprint, please be sure to hyperlink form to indicate the original source of the article and author information and this statement
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
Key words: DWR javascript: void (0); >ajax


Overview

This article describes the use of Open source project DWR (direct web Remote control) and JavaScript: void (0); The concept of >ajax (asynchronous JavaScript and XML) to improve usability of Web applications. The author step by step to show how Dwr makes JavaScript: void (0); The application of >ajax is simple and fast. (1600 words; June 20, 2005)

Javascript: void (0); >ajax, or asynchronous JavaScript and XML, describes a development technique that uses mixed HTML (or XHTML) and cascading style sheets as expression information to create interactive Web applications; Document Object Model (DOM), JavaScript, Dynamically displays and interacts with the presentation information, and the XMLHttpRequest object asynchronously exchanges and processes data with the Web server.

Many examples on the Internet show the necessary steps to use XMLHttpRequest to interact with the server side within an HTML file. When XMLHttpRequest code is written and maintained manually, developers must deal with a number of potential problems, especially those similar to Cross-browser implementations of the DOM. This will lead to a time-consuming effort to encode and debug JavaScript code, which is obviously unfriendly to developers.

The DWR (direct web Remote Control) project is an open source solution under the Apache license that provides for those who want to use JavaScript in an easy way: void (0); Developers of >ajax and XMLHttpRequest. It has a set of JavaScript features that simplify the method of invoking Java objects on an application server from an HTML page. It manipulates different types of parameters while maintaining the readability of the HTML code.

DWR is not an insertion of a design, nor does it force an object to use any kind of inheritance structure. It fits well with the application within the servlet framework. For developers lacking DHTML programming experience, DWR also provides a JavaScript library containing frequently used DHTML tasks, such as assembly tables, filling the Select Drop-down box with item, and changing the content of HTML elements, such as <div> and <span >
The DWR website is detailed and has a lot of documentation, which is also the basis of this article. Some examples are used to show how DWR uses and uses its library to accomplish what it does.

This article gives readers a glimpse of how a Web application using DWR is built step-by-step. I'll show you the necessary details for creating this simple example application that is downloadable and can be seen in your environment to see how DWR works.
Note: Find out about JavaScript: void (0); >ajax information is not difficult; There are several articles and blog entries on the Web page that cover this topic, each of which tries to point out and comment on different aspects of the concept. In the Resources section, you'll find interesting links to examples and articles to learn about JavaScript: void (0); More content of the >ajax.

Example Application
This article uses a sample application that simulates a Toronto apartment rental search engine. Users can select a set of search criteria before searching. To improve interactivity, JavaScript: void (0); The following two types of >ajax are used:
• Application notification How many search results will be returned by the user with his choice. This number is updated in real time-using JavaScript: void (0); >ajax-when the number of bedrooms and bathrooms the user chooses, or when the price range changes. When the standard search results are not or too long, it is not necessary for users to click the Search button.
• Database query and retrieve results from JavaScript: void (0); >ajax completed. The database performs a search when the user presses the Display results button. In this way, the application looks more responsive, and the entire page does not need overloading to display the results.

Database
The database we use is hsql, a small resource-intensive Java SQL Database engine that can be bundled with Web applications without the need for installation and configuration. An SQL file is used to create an in-memory table and add some records when the context of the Web application starts.

Java class
The application contains two main classes called Apartment and Apartmentdao. The Apartment.java class is a simple Java class with attributes and Getter/setter methods. Apartmentdao.java is a 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 the Java database join call to get the total number of apartments and a list of available apartments that meet the user's request.

DWR Configuration and use
The use of DWR is simple: dwr jar files are copied into the Web-inf/lib directory of the Web application, a servlet declaration is added to Web.xml, and a dwr configuration file is created. A separate jar file needs to be used in the distribution of DWR. You must add the DWR servlet to the Web-inf/web.xml section of the application.
<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-to set the debug parameter to True in the servlet description section. When DWR is in debug mode, you can see all of the accessible Java objects from the HTML Web page. A Web page that contains a list of available objects appears on the/webapp/dwr URL, which shows the object's public methods. The listed methods can be invoked from the page, allowing you, for the first time, to run the object on the server method. The following illustration shows how the Debug page looks:


Debug Page

Now you have to let dwr know what object will receive the request through the XMLHttpRequest object. This task is done 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. From a design point of view, DWR allows access to all public methods of the advertisement class, but in our case we only allow access to several methods. Here is the configuration file for our sample:
<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 implements the two goals in our example. First, the,<convert> tag tells Dwr to convert the type of the Dwr.sample.Apartment object to a federated array because, for security reasons, the normal bean is not converted by default DWR. The second,<create> tag lets dwr expose Dwr.sample.ApartmentDAO classes to JavaScript calls; we use JavaScript files in the page to be defined by JavaScript properties. We must pay attention to the <include> tag, which indicates which methods of the Dwr.sample.ApartmentDAO class are available.

html/jsp Code
Once the configuration is complete, you can start your Web application, and DWR will be ready to invoke the desired method from your HTML or Java server-side page (JSP), and you do not need to 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 our code:

<script src= ' dwr/interface/apartmentdao.js ' ></script>
<script src= ' dwr/engine.js ' ></script>
<script src= ' dwr/util.js ' ></script>


We notice that when the user changes the search criteria, this is JavaScript: void (0); >ajax first application in the sample program; as he saw, the number of apartments available was updated when the standards changed. I created two JavaScript functions: Called when the value in a Select Drop-down box changes. The apartmentdao.countapartments () function is the most important part. The most interesting is the first parameter, the Loadtotal () function, which indicates the JavaScript method that DWR will invoke when it receives a return from the server. Loadtotal is then called to display the results in the <div> of the HTML page. The following are the JavaScript functions that are used in this interaction scenario:

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;
}


Clearly, users want to see a list of apartments that match his search criteria. Then, when the user is satisfied with his search criteria and the total number is valid, he presses the button that displays the result, 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 holds the search return results, obtains the required parameters from the user interface, and passes these parameters to the Apartmentdao object created by DWR. The database query is then executed, filltable () is invoked, resolves the object returned by DWR (apartment), and then displays it to the page (apartmentsbody).

Security Factors
To keep the sample brief, the Apartmentdao class remains as simple as possible, but such a class typically has a set of methods for manipulating data, such as insert (), update (), and delete (). DWR exposes all public methods to all HTML page calls. It is unwise to expose your data access layer like this for security reasons. Developers can create a façade to centralize communication between all JavaScript functions and the underlying business components, which limits the ability to expose too much.

Conclusions
This article only allows you to use JavaScript, supported by DWR, in your project: void (0); >ajax opened his head. Dwr lets you focus on how to improve your application's interaction model, eliminating the burden of writing and debugging JavaScript code. Using JavaScript: void (0); The most interesting challenge for >ajax is to define where and how to improve availability. DWR is responsible for manipulating the communication between the Web page and your Java object, which helps you focus entirely on how to make your application's user interface more user-friendly,
I would like to thank Mircea Oancea and Marcos Pereira, who read this article and gave a very valuable return.

Resources
javaworld.com:javaworld.com
· Matrix-java Developer Community: http://www.matrix.org.cn/
onjava.com:onjava.com
• Download all the source code for 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
· The JavaScript: void (0); >ajax: A new path to Web Apps ": Jesse James Garrett (Adaptive Path, 2005.2): http://www.adaptivepath.com/publications/essays/ archives/000385.php
· "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 Work Example: Http://www.fiftyfoureleven.com/resources/programming/xmlhttprequest/examples
· "Available XMLHttpRequest practices" Thomas baekdal (baekdal.com, 2005.3): http://www.baekdal.com/articles/Usability/ usable-xmlhttprequest/
·" XMLHttpRequest Use Guide "Thomas baekdal (baekdal.com, 2005.2): http://www.baekdal.com/articles/Usability/ xmlhttprequest-guidelines/

<

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.