Simple application of DWR

Source: Internet
Author: User
Tags javascript array

1. Preface

What is DWR? DWR is an AJAX framework in the Java EE domain that enables developers to develop AJAX applications more easily with Dwr's help. With Dr's help, developers can invoke remote Java methods in the browser's JavaScript code, just as these Java methods are defined on the client side.

The DWR framework allows client-side JavaScript code to invoke a remote Java method directly, a call that is very similar to the WebService technology called RPC (remoteprocedure call, remote procedure call), so Dwr is also known as the RPC-style AJAX framework.

The DWR framework mainly consists of the following two parts.

1) The client has Javascipt, which allows client-side JavaScript to directly invoke the Java method of the remote server. In addition to this, DWR provides handy tool functions to simplify DOM operations.

2) The servlet running on the server handles the user request and delegates the user request to the actual Java object for processing, and is responsible for returning the processing result to the client.

The rationale is that when a developer calls a remote Java method directly, DWR is responsible for translating the call into the corresponding Ajax request and using XMLHttpRequest to send the request to the remote server. When the server processing is complete, DWR is responsible for data transfer and conversion.


2. Download Dwr file

1) Log in to the Http://directwebremoting.org/dwr/downloads site and download the Dwr file.


1) The Dwr.jar file under the Web-inf\lib directory in the above decompression path is supervised to the web-inf\lib of the Web application.

3. Configure Web. xml

Successfully installing DWR requires modifying the Web. xml file, modifying the Web. xml file to ensure that a particular request is forwarded to DWR's core servlet processing, while the Dwr.xml file is responsible for defining the correspondence between Java classes and JavaScript objects.

<?xml version= "1.0" encoding= "GBK"? ><web-app 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/javaeehttp://java.sun.com/ Xml/ns/javaee/web-app_2_5.xsd "version=" 2.5 "><!--configuring DWR's core servlet--><servlet><!-- Specifies the name of the DWR core servlet--><servlet-name>dwr-invoker</servlet-name><!--Specifies the implementation class of the DWR core servlet-->< servlet-class>org.directwebremoting.servlet.dwrservlet</servlet-class><!--  Specifies that the DWR core servlet is in the debug state--><init-param><param-name>debug</param-name><param-value>true </param-value></init-param></servlet><!--Specify the URL mapping for the core servlet--><servlet-mapping> <servlet-name>dwr-invoker</servlet-name><!--Specifies the URL of the core servlet map--><url-pattern>/leedwr/* </url-pattern></servlet-mapping></web-app>
4. Add a Dwr.xml file

1)          In addition, you must add a dwr.xml, which is responsible for defining the correspondence between Java classes and JavaScript objects.

<?xml version= "1.0" encoding= "GBK"?><!--Specify the DTD for the DWR configuration file--><! DOCTYPE dwr Public "-//getahead limited//dtd Direct Web Remoting 3.0//en" "Http://getahead.org/dwr/dwr30.dtd" ><!- -The root element of the DWR configuration file is the DWR--><dwr><allow><!--Create a Java instance using the new key to specify that the JavaScript object created is named hello-->< Create creator= "new" javascript= "Hello" ><!--Use the Class property to specify the implementation class that created the Java instance--><param Name= "class" value= " COM.OWEN.DWR.HELLODWR "/></create><!--using bean converters for Com.owen.dwr.domain.Person classes--><convert Converter= "Bean" match= "Com.owen.dwr.domain.Person"/><!--to Com.owen.dwr.domain.Cat using the object Converter-->< Convert converter= "Object" match= "Com.owen.dwr.domain.Cat" ><!--Specify Force= "true" to enforce access to private properties using reflection--><param Name= "Force" value= "true"/></convert></allow><signatures><! [Cdata[import java.util.list;import Com.owen.dwr.hellodwr;import Com.owen.dwr.domain.Person; Hellodwr.sendlistnogeneric (list<person>);] ></signatures></dwr> 

2) Dwr.xml File description

A) in the above configuration file, the most important element is the <allow.../> element, if a dwr.xml file does not have a defined <allow.../> element, or if the <allow.../> element is empty, then DWR will not be able to do anything. The elements commonly used in <allow.../> elements are <create.../> and <conert.../>, where <create.../> is used to define how to convert a Java class into a JavaScript object, and <convert.../> defines how transformations between Java objects and JavaScript objects are accomplished.

b) Dwr uses reflection to determine conversions between Java instances and JavaScript objects. At the time, the parameter type information is not very clear, or the parameter is a collection object, and the generic is not used to restrict the type of the collection element, which requires that these types be explicitly specified in the <signatures.../> element of the Dwr.xml file.

5. Create the corresponding class

In the Dwr.xml file, we have added several classes, so this time we need to provide these classes.

1) Cat.java

/** * Entity Cat * @author Owenwilliam 2016-5-8 * @version 1.0 */public Class Cat{//cat Private property of the private String name;//constructor public Cat (String name) {this.name = name;}}

2) Person.java

Package com.owen.dwr.domain;/** * Entity person * @author Owenwilliam 2016-5-8 * @version 1.0 */public Class person{//private FIELDPR Ivate string name;//parameterless constructor public person () {}//Initializes all member variables of the constructor public person (String name) {this.name = name;} Name setter and getter method public void SetName (String name) {this.name = name;} Public String GetName () {return this.name;}}

3) Hellodwr.java

 Package Com.owen.dwr;import java.util.*;import com.owen.dwr.domain.*;/** * @author owenwilliam 2016-5-8 * @version 1.0 * /public class hellodwr{//The first simple Hello method public string Hello (string name) {return name + "Hello!" You have started the Dwr learning journey and wish you a happy learning ... ";} A method that uses a JavaBean as a parameter public String sendobj (person p) {return p.getname () + "Hello! You have learned to use the JavaBean parameter ... ";} Returns the method of the JavaBean instance public person Getbean (String name) {return new person (name);} Returns a generic Java object that provides a setter and getter method for its properties public cat GetObject (String name) {return new Cat ("Server side" + name);} Returns a collection object public list<person> getpersonlist () {list<person> result = new arraylist<person> (); Result.add (New Person ("set AAAA")), Result.add (New Person ("collection bbbb")), Result.add (New Person ("set CCCC"), return result; Returns an array object public person[[] Getpersonarray () {person[] result = new Person[3];result[0] = new person ("array aaaa"); result[1] = n EW person ("array bbbb"); result[2] = new Person ("array cccc"); return result; Returns a Map object public map<string, Person> GetpersoNMap () {//Create a Map object map<string, person> result = new hashmap<string, person> ();//fill in the contents of the Map object Result.put (" First ", New person (" Map aaaa ")), Result.put (" second ", New Person (" map BBB ")), Result.put (" Third ", New person (" Map CCCC ")) ;//return mapreturn result;} The parameters of the remote method are the collection public String sendlist (list<person> pl) {string result = ""; for (person P:PL) {result + = P.getname () + "<br/>";} return result;} The parameters of the remote method are the collection without generics public String sendlistnogeneric (List pl) {string result = ""; for (Object p:pl) {result + = (person) p). GE Tname () + "<br/>";} return result;} The parameters of the remote method are the collection public String sendmap (map<string, person> pmap) {string result = ""; for (string Key:pmap.keySet ()) {RE Sult + = "Key" + key + "Its value is:" +pmap.get (Key). GetName () + "<br/>";} return result;}}
6. Create JS file

Create a JS file named Hellodwr.js, this file can be called directly in the Java class method. Calls like Hello.hello (name, CB) are called directly.

-------------send a simple string parameter, return the normal string--------------function SendMessage () {//Gets the value of the name element in the page var name = document.getElementById ("name"). value;//call the remote method, CB is the callback function Hello.hello (name, CB)}function CB (data) { document.getElementById ("Show"). InnerHTML = data;} -----------sends a JavaBean object as a parameter, returns a normal string------------function SendObject () {var namevalue = document.getElementById (" Name "). value;//calls the remote method, using the JavaScript object as the parameter Hello.sendobj ({Name:namevalue}, CB);} ----------------Call Returns the JavaBean method-----------------function Getbean () {var name = document.getElementById ("name"). value;//calls the remote method, BEANCB is the callback function Hello.getbean (name, BEANCB)}function BEANCB (data) {//server method returns the JavaBean object, The client's data is a JavaScript object document.getElementById ("show"). InnerHTML = Data.name + ", Hello, you have learned to use JavaBean return value";} ----------------Call Returns the GetObject method---------------function GetObject () {var name = document.getElementById ("name"). value;//calls the remote method, OBJCB is the callback function Hello.getobject (name, OBJCB)}function OBJCB (data) {//server method returns a non-JavaBean object, The client's data is a JavaScript object document.geteLementbyid ("Show"). InnerHTML = Data.name + ", is the name of the cat returned from the server"; ---------------call a method that returns a collection--------------function getbeanlist () {//calls a remote method, LISTCB returns a callback function Hello.getpersonlist (LISTCB) ;} The remote Java method returns the list object, the collection element is a JavaBean object//The data here is a JavaScript object array function LISTCB (data) {var result= ';//iterate through each array element for ( var i = 0; i < data.length; i + +) {result + = Data[i].name + "<br/>";} document.getElementById ("Show"). InnerHTML = result;} ---------------Call method that returns an array--------------function Getbeanarray () {Hello.getpersonarray (ARRAYCB);} function ARRAYCB (data) {var result = "";//The following data is the return value of the remote Java method,//data is a number of arrays, traversing the array. for (var i = 0; i < data.length; i + +) {//access the array element sequentially, the array element is a JSON-formatted object, access its Name property, result + = Data[i].name + "<br/>";} document.getElementById ("Show"). InnerHTML = result;} ---------------Call method that returns a Map object-------------function Getbeanmap () {hello.getpersonmap (MAPCB);} The remote Java method returns the Map object, the collection element is a JavaBean object//The data here is a JavaScript object, and each property value is a JavaScript object function MAPCB (data) {var result= ' ; for (var key in data) {RESult + = "key is" + key + "and its value is:" + data[key].name + "<br/>";} document.getElementById ("Show"). InnerHTML = result;} ---------------call method to send collection-------------------function sendbeanlist () {//create JavaScript array var args = [{name: "Client AAA"},{ Name: "Client BBB"},{name: "Client CCC"}];//Java method requires a list parameter to call the remote method hello.sendlist (args, SENDLISTCB) as an argument to the JavaScript array;} function SENDLISTCB (data) {document.getElementById ("show"). InnerHTML = data;} ---------------call to send a collection without generic restrictions--------------------function sendbeanlistnogeneric () {//create JavaScript array var args = [{ Name: "Client AAA"},{name: "Client bbb"},{name: "Client CCC"}];//Java method requires a list parameter, Call the remote method Hello.sendlistnogeneric (args, SENDLISTCB) with a JavaScript array as a parameter;} ---------------call method to send map-------------------------function Sendbeanmap () {//Create JavaScript object var args = {First:{name : "Client AAA"},second:{name: "Client bbb"},third:{name: "Client CCC"}};//Java method requires the map parameter to invoke the remote method Hello.sendmap as a parameter of the JavaScript object ( args, SENDMAPCB);} function SENDMAPCB (data) {document.getElementById ("show"). InnerHTML = data;}
7. Creating front-end HTML files

The HTML file is the method to invoke in Hellodwr.js.

<! DOCTYPE Html>8. Project Creation diagram

9. Implementation results

SOURCE download: [Email protected]:owenwilliam/hellodwr.git









Simple application of DWR

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.