DWR (II) -- reverse Ajax

Source: Internet
Author: User

The previous article (DWR description 1) mentioned that DWR allows JavaScript to access the Java method on the server, which makes Ajax easier to use, dwr2.0 adds a very powerful function-reverse Ajax, that is, the server-side Java method can obtain the web context of the browser and call the JavaScript method, transmits the server-side data asynchronously to the browser. This article will show this feature through a demo. This demo provides a function similar to the real-time data update function in the stock trading system. In fact, it is implemented through the publishing-subscription mode. That is to say, the client subscribes to a topic, and the server sends data regularly and asynchronously to the browser that subscribes to the topic through a thread, thus realizing this real-time update function. Click here for the project codeDownload:Reverseajaxdemo

We know that the client browser can connect to the Web server at any time and request resources from the server, but the server does not have this capability. It cannot actively establish a connection on the client browser, and actively send data to the browser. DWR supports sending data from the server to the client:

1. Round Robin. The client sends a request to the server in each cycle to check whether there is any data update on the server. If so, it requests data from the server.

2. Comet: Server pushing Method Based on HTTP persistent connection. After the client sends a request to the server, the server sends the data to the client through response, but does not close this response, but always sends the latest data to the client browser through response, until the client browser is closed.

3. Piggyback (return ). The server queues the latest data and sends it to the client after receiving the next request from the client.

The three methods have their own advantages and disadvantages, while DWR supports both round robin and comet.

First, let the DWR program support reverse Ajax. You only need to add an initialization parameter to dwrservlet in Web. xml:

<servlet><servlet-name>dwr-invoker</servlet-name><servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class><init-param><param-name>activeReverseAjaxEnabled</param-name><param-value>true</param-value></init-param>...</servlet>

In addition, this demo uses the tibco general interface (GI) Ajax framework. Therefore, we need to introduce the jsx component library and in the gidemo directory in config. XML and appcanvas. XML defines the components that need to be used (mainly using the matrix data table component), for tibco GI, see http://www.tibco.com/devnet/index.html

The core of this demo is the publisher. Java on the server. In this class, you first obtain the web context to access the application through org. directwebremoting. webcontext:

Webcontext = webcontextfactory. Get ();
Servletcontext = webcontext. getservletcontext ();
Servercontext = servercontextfactory. Get (servletcontext );

Webcontext. getscriptsessionsbypage ("");

Here, we use the webcontext class to obtain the web context of the DWR application, use servletcontext to obtain the context of the dwrservlet, and use the web context to obtain the scriptsession of the client browser accessing the application. Through scriptsession, you can send the command to execute the js method to the client browser on the server side and send the server-side data to the js method. The specific usage is as follows:

Collection sessions = servercontext. getscriptsessionsbypage ("/reverseajaxdemo/index.html ");
Scriptproxy proxy = new scriptproxy (sessions );
Corporation Corp = tolerations. getnextchangedcorporation ();
Proxy. addfunctioncall ("openajax. Publish", "gidemo", "corporation", Corp );

This code first obtains the scriptsession of all client browsers that access the/reverseajaxdemo/index.html resource through the getscriptsessionsbypage method, and creates a proxy (scriptproxy) for these sessions. Through this proxy, the client executes openajax. publish js method (see openajax. JS ). Addfunctioncall is the server-side method that sends the js method to the client. The first parameter is the signature of the js method, followed by the parameters of the js method. "Gidemo" is the topic published on the server, "coporation" is the variable to be released, and Corp is the real-time data to be released. Corp. This object is randomly generated (see the corporation and tolerations classes), publish. java starts a worker thread, which continuously generates Corporation data and releases it to the client.

The following code is the core part of the HTML page:

<Div style = "width: 100%; Height: 280px;" id = "gidemo">
<Script. type = "text/JavaScript"
Src = "jsx/JS/jsx30.js"
Jsxapppath = "gidemo"
Jsxlt = "true"> </SCRIPT>
</Div>

This piece of code mainly uses the GI matrix component, which can dynamically load data. In addition, index. JS is introduced on the page. There are two main methods:

Function giloaded (){
Openajax. subscribe ("gidemo", "corporation", objectpublished );
DWR. Engine. setactivereverseajax (true );
}

Function objectpublished (prefix, name, handlerdata, Corporation ){
VaR matrix = giapp. getjsxbyname ("matrix ");
VaR inserted = matrix. getrecordnode (Corporation. jsxid );
Matrix. insertrecord (Corporation, null, inserted = NULL );

// There are always ways to get a table to repaint.
// One easy way is to ask it to repaint:
// Matrix. repaintdata ();

// But we are going for a fancy option that does highlighting
For (VAR property in corporation ){
If (property! = "Jsxid "){
VaR x = matrix. getcontentelement (Corporation. jsxid, property );
If (OX ){
VaR current = ox. innerhtml;
If (current! = "" + Corporation [property]) {
Ox. style. backgroundcolor = "# fde4eb ";
VaR callback = function (Ele ){
Return function () {ELE. style. backgroundcolor = "# ffffff ";};
} (OX );
SetTimeout (callback, 1000 );
Ox. innerhtml = Corporation [property];
}
}
}
}
}

The giloaded method subscribes to data with the topic "gidemo" through the openajax. subscribe method (the data is published by the server-side Java method ). Objectpublished is a callback method, indicating the page changes after data is obtained. This callback method is very simple. It only changes the color of the changed data in the matrix component, and implements the Real-Time reminder data update function.

In addition, the server also has a listener publisherservletcontextlistener, which is used to close the publisher thread when appropriate. This listener should be used in combination with the other two DWR listeners. You only need to declare it in Web. xml:

<Listener>
<Listener-class> org. directwebremoting. servlet. efficientshutdownservletcontextattributelistener </listener-class>
</Listener>
<Listener>
<Listener-class> org. directwebremoting. servlet. efficientshutdownservletcontextlistener </listener-class>
</Listener>
<Listener>
<Listener-class> gidemo. publisherservletcontextlistener </listener-class>
</Listener>

Finally, let's take a look at the DWR ing relationship DWR. xml:

<DWR>
<Allow>
<Create creator = "new" javascript = "JDate">
<Param name = "class" value = "Java. util. Date"/>
</Create>
<Create creator = "new" javascript = "publisher" Scope = "application">
<Param name = "class" value = "gidemo. publisher"/>
</Create>
<Convert converter = "Bean" match = "gidemo. Corporation"/>

<! -- This is a bad idea for live, but can be useful in testing -->
<Convert converter = "exception" match = "Java. Lang. Exception"/>
<Convert converter = "Bean" match = "Java. Lang. stacktraceelement"/>
</Allow>
</DWR>

Pay attention to the configuration in the red part. DWR allows mutual conversion between custom Java types and JS objects, but declares the converter.

The following is the result of the program running:

This example is complex and aims to help you understand the principle of reverse Ajax. At the beginning of the next article, we will use some simple examples to illustrate the usage of DWR reverse Ajax.

References:

Http://getahead.org/dwr/reverse-ajax

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.