Preliminary technical implementation of DWR's reverse Ajax

Source: Internet
Author: User

DWR's reverse Ajax mainly includes two modes: Active Mode and passive mode. The active mode includes polling and comet, while the passive mode only includes piggyback.

The so-called piggyback indicates that if there is anything in the background that needs to be pushed to the foreground (that is, calling the page's js method), it will wait until that page carries out the next Ajax request, append the content to be pushed to the page after the request.

Polling refers to sending Ajax requests to the server regularly by the browser, asking whether there is any content to be pushed in the background, and then the server will return the pushed content. This method is similar to sending an Ajax request directly on the page through a timer, and then querying whether there is any change in content in the background. However, after using DWR, this part of work was completed by the framework.

In comet mode, when the server establishes a connection with the browser and sends the page content to the browser, the corresponding connection is not closed, but is temporarily suspended. If there is any new content that needs to be pushed to the client, the data will be directly transferred through the pending connection.

Through the above explanation, we can see that these three modes have their respective advantages and disadvantages. From the perspective of the number of client requests, piggyback is certainly the best mode. There are no additional network requests in the request. The changed content will be transmitted back to the page only when the next request page is initiated. But this also leads to the delay of the push content, because you have no way to know when the next request of the page will be initiated, and maybe the page will never have the next request. In polling mode, network requests are the most frequent, because at this time, the page needs to send a request to ask whether there is any updated content in the background. Although this mode can reduce the number of requests per unit time by increasing the request interval, this will also lead to an increase in the interval between page response and background content changes, there is a conflict between them. The specific request interval must be configured according to the requirements of specific projects. For example, the server can bear the request interval and the page content needs to be refreshed. The response speed of the comet method should be the fastest. Once the content needs to be pushed in the background, it can be pushed to the foreground immediately through a connection that has not been closed before. However, the number of connections provided by the server is certain. When a large number of suspended connections are not closed, new connection requests may not be accessible, thus affecting the service quality.

I. Configuration

1) piggyback

DWR uses the passive mode piggyback by default. To use this mode, no additional configuration is required.

2) comet Mode

If you need to adopt the active mode, you need to configure the following parameters in the DWR servlet in Web. xml:

<Servlet>

<Servlet-Name> DWR-invoker </servlet-Name>

<Display-Name> DWR servlet </display-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 the onload event of the page body that needs to receive the push content, you need to call:

DWR. Engine. setactivereverseajax (true );

Method to start the reverseajax function of the page. In this case, the comet method is used by default to push the page content.

3) Polling Mode

To use the polling method, you only need to add the following parameters to the servlet Parameters Based on the comet method:

<Init-param>

<Param-Name> org. directwebremoting. Extend. serverloadmonitor </param-Name>

<Param-value> org. directwebremoting. impl. pollingserverloadmonitor </param-value>

</Init-param>

The default request interval on the page is 5 seconds. If you need to configure it, use the following parameters:

<Init-param>

<Param-Name> disconnectedtime </param-Name>

<Param-value> 60000 </param-value>

</Init-param>

Note: This sets the request interval to 60 seconds.

Ii. Call Method

The background can push content in the following way:

Scriptbuffer script = new scriptbuffer ();

Script. appendscript ("add the string of js code to be executed on the page ");

Servercontext sCTX = servercontextfactory. Get (servletcontext );

If (sCTX! = NULL)

{

Collection pages = sCTX. getscriptsessionsbypage ("add the relative path of the page to be pushed, such as/book/list. jsp ");

Iterator it = pages. iterator ();

While (it. hasnext ())

{

Scriptsession session = (scriptsession) it. Next ();

Session. addscript (SCRIPT );

}

}

The servletcontext can be passed in either through foreground requests or through this class to implement the spring servletcontextaware interface, which is injected by spirng. In addition, the context of DWR has been established before the servercontextfactory. Get (servletcontext) method is called.

After completing the above work, you will be able to enjoy the pleasant experience that DWR has brought you through reverse Ajax. You can operate the browser as conveniently as the server directly operates the client in CS mode.

Iii. Implementation Method

Simulate the content of <simplest DWR example> I wrote earlier to create the WEB Project testajax. This routine mainly enables the server to actively refresh the current time on the client page and generate a random number in the editing box.

1) clock. Java code

Package COM. test. ajax; import Org. directwebremoting. servercontextfactory; import Org. directwebremoting. browser; import Org. directwebremoting. UI. DWR. util; import Java. util. date; import Java. util. concurrent. scheduledthreadpoolexecutor; import Java. util. concurrent. timeunit; publicclass clock implements runnable {protectedtransientbooleanactive = false; Inti = 0; Public clock () {scheduledthreadpoolexecut Or executor = new scheduledthreadpoolexecutor (1); executor. scheduleatfixedrate (this, 1, 1, timeunit. seconds);} publicvoid run () {If (active) {setclockdisplay (New Java. text. simpledateformat ("mm DD, yyyy, HH, mm, SS seconds ")). format (new date () ;}}/*** called from the client to turn the clock on/off */publicsynchronizedvoid toggle () {I ++; active =! Active; system. Out. println ("toggle clicked! "+ I); system. out. println ("active:" + active); If (active) {setclockdisplay ("started");} else {setclockdisplay ("STOPPED ");}} publicvoid setclockdisplay (final string output) {string page = servercontextfactory. get (). getcontextpath () + "/index. JSP "; browser. withpage (page, new runnable () {publicvoid run () {util. setvalue ("clockdisplay", output); double dvalue = math. random (); string strvalue = string. valueof (dvalue); util. setvalue ("pointvalue", strvalue );}});}}

2) DWR. XML Code

<?xml version="1.0" encoding="UTF-8"?>  <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN" "http://getahead.org/dwr/dwr30.dtd">  <dwr><allow><create creator="new" javascript="Clock" scope="application"><param name="class" value="com.test.ajax.Clock"/></create></allow></dwr>

3) DWR. XML Code

<? XML version = "1.0" encoding = "UTF-8"?> <Web-app version = "3.0" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-Name> </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> <init-param> <description> whether to activate reverse Ajax </description> <param-Name> activereverseajaxenabled </param-Name> <param-value> true </param- value> </init-param> <description> whether to create a creator whose range is application at Web startup </description> <param-Name> initapplicationscopecreatorsatstartup </Param -Name> <param-value> true </param-value> </init-param> <load-on-startup> 1 </load-on-startup> </Servlet> <servlet-mapping> <servlet-Name> DWR-invoker </servlet-Name> <URL-pattern>/DWR/* </url-pattern> </servlet-Mapping> <welcome-file-List> <welcome-File> index. JSP </welcome-File> </welcome-file-List> </Web-app>

4) index. jsp code

<% @ Page Language = "Java" contenttype = "text/html; charset = gb18030" pageencoding = "gb18030" %> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en"> <HTML> 

5 ),

Figure 3-1 initial Page

Figure 3-2 dynamic data refresh

 

Iv. Future Use

Under normal circumstances, DWR calls the server-side JavaBean object method using the forward request/response mode, also known as the PULL model. The client JavaScript calls the JavaBean method, the returned results update the HTML elements on the page through the callback method to display the monitoring data. This positive mode is suitable for common management system applications, but applications that require high real-time monitoring systems are insufficient. The reverse mode is the PUSH model, which is the best way to adapt to the monitoring system. The server component pushes the acquired monitoring data to the Web.
The client does not need the client to actively request, but passively receive the request. Therefore, you can update and display data without refreshing pages on the web layer.

Figure 4-1 architecture of a typical monitoring Web process

End

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.