First understanding of DWR Ajax practices DWR

Source: Internet
Author: User
DWR (Direct Web remoting) is a web Remote Call framework. using this framework can make Ajax development very simple. using DWR, you can use JavaScript on the client side to directly call the Java method on the server side and return the value to Javascript, just like calling it directly on the local client (DWR dynamically generates javascrip code based on Java classes ). the latest version of dwr0.6 adds many features, such as support for automatic Dom trees configuration, support for spring (Remote JavaScript call of spring bean), and better browser support, an optional commons-logging log operation is also supported.

The above is taken from open-open. After reading it for a few days, it is indeed a very good project. It translates Java into JavaScript through reflection, and then uses the callback mechanism, javascript is easy to call Java code.

The general development process is as follows:
1. Write the Business Code, which is irrelevant to DWR.
2. Confirm which classes and methods in the Business Code are directly accessed by JavaScript.
3. Compile the DWR component and encapsulate the method in step 2.
4. Configure the DWR component to the DWR. xml file. If necessary, configure convert to convert Java and JavaScript types.
5. Using the reflection mechanism, DWR converts the class in Step 4 into JavaScript code and provides it to the front-end page for calling.
5. Compile the webpage, call the related methods in Javascript in step 5 (indirectly call the methods of related classes on the server side), execute the business logic, and return the execution results using the callback function.
6. After the execution result is obtained in the callback function, you can continue to write JavaScript Code related to the business logic.

The following is an example of user registration. (Note: This example is only used for demonstration, indicating the use of DWR. The class design is not optimal ).

1. first introduce the relevant Java classes

User: User class,
Public class user {
// Login ID, which is unique in the primary key
Private string ID;
// Name
Private string name;
// Password
Private string password;
// Email
Private string email;

// The getxxx and setxxx methods are as follows:
.......
}

Userdao: Implements user database access. Here is a demo to write test code.
Public class userdao {
// Store the stored data
Private Static map datamap = new hashmap ();

// Permanent user
Public Boolean save (User user ){
If (datamap. containskey (user. GETID ()))
Return false;
System. Out. println ("start to save the user ");
System. Out. println ("ID:" + User. GETID ());
System. Out. println ("Password:" + User. GetPassword ());
System. Out. println ("name:" + User. getname ());
System. Out. println ("Email:" + User. getemail ());
Datamap. Put (user. GETID (), user );
System. Out. println ("End of user saving ");
Return true;
}

// Search for users
Public user find (string ID ){
Return (User) datamap. Get (ID );
}
}

Dwruseraccess: The DWR component, which is provided for JavaScript access.

Public class dwruseraccess {

Userdao = new userdao ();

Public Boolean save (User user ){
Return userdao. Save (User );
}

Public user find (string ID ){
Return userdao. Find (ID );
}
}

The following describes the procedure of program execution.

1. Enter the relevant registration information, such as ID, name, password, and email, and click Submit.
2. JavaScript code execution starts. Based on the information filled in by the user, call the dwruseraccess class save method of dwruseraccess. js provided by DWR to save the registration information.
3. Use the find method in dwruseraccess. jsp to call the find method in the dwruseraccess class on the server side and execute user information search.

Note: In the preceding execution process, dwruseraccess is called by DWR and is a DWR component. Therefore, you need to configure the dwruseraccess class to DWR.

Next, we will explain how to configure the DWR test environment.

1. Create a New webapp named testapp
2. Copy DWR. jar to the lib directory of testapp's WEB-INF
3. Compile the above user, userdao, and dwruseraccess classes and put them in the classes directory.
4. Configure the servlet in Web. xml and adapt the path to the DWR directory, as shown below:
<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>
<Init-param>
<Param-Name> scriptcompressed </param-Name>
<Param-value> false </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>

The above configuration can intercept all requests directed to DWR in testapp. We will introduce this interceptor later.

5. Create a DWR. xml file under the WEB-INF with the following content:
<? XML version = "1.0" encoding = "UTF-8"?>
<! Doctype DWR public "-// getahead limited // DTD direct Web remoting 1.0 //" http://www.getahead.ltd.uk/dwr/dwr10.dtd ">

<DWR>
<Allow>
<Create creator = "new" javascript = "dwruseraccess">
<Param name = "class" value = "test. dwruseraccess"/>
</Create>
<Convert converter = "Bean" match = "test. User"/>
</Allow>
</DWR>

Here we configure dwruseraccess to DWR. In the create element, creater = "new" indicates that each time dwruseraccess is called, a new class is required. Javascript = "dwruseraccess ", indicates that the specified cirpt file provided to the front-end page is dwruseraccess. JS.

The convert element is used for data type conversion, that is, the conversion between the Java class and Javascript. Because the user object is exchanged with the foreground, bean conversion is required. We will introduce this class later.

4. Compile the test HTML page test.html
<! Doctype HTML public "-// W3C // dtd html 4.0 transitional // en">
<HTML>
<Head>
<Title> DWR test </title>
<Meta http-equiv = Content-Type content = "text/html; charset = gb2312">
<SCRIPT src = "/oblog312/DWR/engine. js"> </SCRIPT>
<SCRIPT src = "/oblog312/DWR/util. js"> </SCRIPT>
<SCRIPT src = "/oblog312/DWR/interface/dwruseraccess. js"> </SCRIPT>
</Head>
<Body>
<B> User Registration </B> <br>
------------------------------------------------
<Br>
<Form name = "regform">
Login ID: <input type = "text" name = "ID"> <br>
Command: <input type = "password" name = "password"> <br>
Last name: <input type = "text" name = "name"> <br>
Email: <input type = "text" name = "email"> <br>
<Input type = "button" name = "submitbtn" value = "Submit" onclick = "onsave ()"> <br>
</Form>

<Br>
<Br> <B> user query </B> <br>
------------------------------------------------
<Br>
<Form name = "queryform">
Login ID: <input type = "text" name = "ID"> <br>
<Input type = "button" name = "submitbtn" value = "Submit" onclick = "onfind ()"> <br>
</Form>
<Br>
</Body>
</Html>
<Script language = "JavaScript">
<! --
Function savefun (data ){
If (data ){
Alert ("registration successful! ");
} Else {
Alert ("Login ID already exists! ");
}
}

Function onsave (){
VaR usermap = {};
Usermap. ID = regform. Id. value;
Usermap. Password = regform. Password. value;
Usermap. Name = regform. Name. value;
Usermap. Email = regform. Email. value;
Dwruseraccess. Save (usermap, savefun );
}

Function findfun (data ){
If (Data = NULL ){
Alert ("unable to find user:" + queryform. Id. value );
Return;
}

Alert ("find user,/NID:" + data. ID + ",/npassword:" + data. password + ",/nname:" + data. name + ",/nemail:" + data. email );

}

Function onfind (){
Dwruseraccess. Find (queryform. Id. Value, findfun );
}
// -->
</SCRIPT>

The following describes the JavaScript code on the page.

<SCRIPT src = "/oblog312/DWR/engine. js"> </SCRIPT>
<SCRIPT src = "/oblog312/DWR/util. js"> </SCRIPT>
The two are provided by DWR. You don't have to worry about them. You just need to import them.

<SCRIPT src = "/oblog312/DWR/interface/dwruseraccess. js"> </SCRIPT>
It is the dwruseraccess class we wrote. After reflection by DWR, the JavaScript code generated, it and dwruseraccess. java is corresponding for users to call. In fact, we use this JS file to call the dwruseraccess class on the server.

<Script language = "JavaScript">
<! --
Function savefun (data ){
If (data ){
Alert ("registration successful! ");
} Else {
Alert ("the user name already exists! ");
}
}

Function onsave (){
VaR usermap = {};
Usermap. ID = regform. Id. value;
Usermap. Password = regform. Password. value;
Usermap. Name = regform. Name. value;
Usermap. Email = regform. Email. value;
Dwruseraccess. Save (usermap, savefun );
}

Function findfun (data ){
If (Data = NULL ){
Alert ("unable to find user:" + queryform. Id. value );
Return;
}

Alert ("find user,/NID:" + data. ID + ",/npassword:" + data. password + ",/nname:" + data. name + ",/nemail:" + data. email );

}

Function onfind (){
Dwruseraccess. Find (queryform. Id. Value, findfun );
}
// -->
</SCRIPT>

In this Code, let's take a look at the onsave function. First, it constructs a map, sets the form data to the map, then calls dwruseraccess. Save (usermap, savefun), and executes the save operation. You can note that the Save method in dwruseraccess on the server side is as follows: Boolean save (User user). Its parameter is a user object and a Boolean value is returned; the client-side method is as follows: Save (usermap, savefun). The first parameter usermap is the map object in javascirpt, which is equivalent to the user object on the server (when executed on the server, will be converted to a user object through convert). As mentioned above, DWR uses the callback function to return the execution result. The second parameter savefun is a callback function. In function savefun (data), data is the execution result. Here is a bool value, which is very simple. We can determine whether the data is true and whether the user name is repeated, whether the user is successfully registered.

Let's take a look at the onfind function. The execution result is in the callback function findfun (data), because the server returns a user object, which is converted to a javascript map object through convert,
In findfun, we can easily access this user object through data. ID, Data. Name, Data. Password, and data. Email.

After the configuration is complete, start the server and enter localhost/testapp/test.html in the directory.

1. in the "user registration" form, enter Admin in the ID box, enter 123456 in password, enter chenbug in name, enter chenbug@zj.com in email, click submit button, the dialog box is displayed: "registered successfully ", you can see the following information in the server Background:

Save the user
ID: Admin
Password: 123456
Name: chenbug
Email: chenbug@zj.com
User save ended

Click Submit again to bring up the "Login ID already exists" dialog box ".

2. in the "user query" dialog box, enter the login ID as admin, click the submit button, prompt to find the user, and display the relevant information, enter admin123, and click the submit button, prompting that the user cannot be found.

Now, the test is complete.

Follow-up:
1. Interceptor UK. Ltd. getahead. DWR. dwrservlet
This class intercepts all requests directed to the DWR directory and calls the handler method of processor for processing. ltd. getahead. DWR. impl. under defaprocesprocessor, we can see the detailed processing process.
If (pathinfo. Length () = 0 |
Pathinfo. Equals (htmlconstants. path_root) |
Pathinfo. Equals (req. getcontextpath ()))
{
Resp. sendredirect (req. getcontextpath () + servletpath + htmlconstants. file_index );
}
Else if (pathinfo. startswith (htmlconstants. file_index ))
{
Index. Handle (req, resp );
}
Else if (pathinfo. startswith (htmlconstants. path_test ))
{
Test. Handle (req, resp );
}
Else if (pathinfo. startswith (htmlconstants. path_interface ))
{
Iface. Handle (req, resp );
}
Else if (pathinfo. startswith (htmlconstants. path_exec ))
{
Exec. Handle (req, resp );
}
Else if (pathinfo. equalsignorecase (htmlconstants. file_engine ))
{
File. dofile (req, resp, htmlconstants. file_engine, htmlconstants. mime_js );
}
Else if (pathinfo. equalsignorecase (htmlconstants. file_util ))
{
File. dofile (req, resp, htmlconstants. file_util, htmlconstants. mime_js );
}
Else if (pathinfo. inclusignorecase (htmlconstants. file_deprecated ))
{
File. dofile (req, resp, htmlconstants. file_deprecated, htmlconstants. mime_js );
}
Else
{
Log. warn ("Page not found (" + pathinfo + "). in debug/test mode try viewing/[WEB-APP]/DWR/"); // $ NON-NLS-1 $ // $ NON-NLS-2 $
Resp. senderror (httpservletresponse. SC _not_found );
}

By judging the Servlet Path of the request and processing it, you can refer to it by yourself, which is not discussed in detail here.

2. Bean converter, <convert converter = "Bean" match = "test. User"/>
Decompress DWR. jar and you can see DWR. xml in the path uk/Ltd/getahead/DWR. Some default converters are configured here,
<Converter id = "Bean" class = "UK. ltd. getahead. DWR. convert. beanconverter "/> is the user-class converter used just now. Let's go to the code and see how it is converted between JavaScript and Java.

Open the beanconverter code and locate the function.

Public object convertinbound (class paramtype, inboundvariable IV, inboundcontext inctx) throws conversionexception

Converts a javascript object to a Java object.
Paramtype is the class type. In the preceding example, It is test. user,
Inboundvariable IV is the input value. The passed JavaScript value string can be obtained through IV. getvalue.
Inboundcontext inctx is the context of the entry parameter, used to save the converted Java object.

Because the front-end inputs a javascript map type, and the map must end with {And}, this function starts to judge.
If (! Value. startswith (conversionconstants. inbound_map_start ))
{
Throw new illegalargumentexception (messages. getstring ("beanconverter. missingopener", conversionconstants. inbound_map_start); // $ NON-NLS-1 $
}

If (! Value. endswith (conversionconstants. inbound_map_end ))
{
Throw new illegalargumentexception (messages. getstring ("beanconverter. missingcloser", conversionconstants. inbound_map_start); // $ NON-NLS-1 $
}

In JavaScript, items in map are connected by commas, such as VAR usermap = {ID: 'admin', password: '000000', name: 'chenbug ', email: 'chenbug @ zj.com '}; the key-value pairs of each item are connected by colons,
In the subsequent processing of the convertinbound function, we analyze the map string, use paramtype to construct a Java instance (that is, the user class), and then use reflection, set these key-value pairs to the Java instance and return.
This completes the conversion from JavaScript to Java.

Another function
Public String convertoutbound (Object Data, string varname, outboundcontext outctx) throws conversionexception

It is to convert a Java object to a JavaScript Object (in fact, it is a declaration and a value assignment statement ).
Object Data, which is the Java object to be converted
String varname: The variable name of the object in JavaScript.
Outboundcontext outctx, the context of the output parameter, used to save the converted JavaScript Value

Stringbuffer buffer = new stringbuffer ();
Buffer. append ("Var"); // $ NON-NLS-1 $
Buffer. append (varname );
Buffer. append ("={};"); // $ NON-NLS-1 $
The map type variables are declared here.

The following Code assigns values to variables through reflection:
Buffer. append (varname );
Buffer. append ('.');
Buffer. append (name );
Buffer. append ('= ');
Buffer. append (nested. getassigncode ());
Buffer. append (';');
You can refer to more code on your own.

3. DWR itself provides a test environment. After configuration, you can enter the http: // localhost/testapp/DWR/index.html address in IE to view the configured DWR components, and perform relevant tests.

Test app http://waplife.cn/testApp.rar

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.