---
title: "论DWR在Java Web快速开发中的重要性"
author: "stephen4留雨"
date: "2013-11-09T15:33:00Z"
tags: []
slug: "dwr-java-web"
draft: false
lastmod: "2014-05-15T16:16:04Z"
id: 2066922
url: "https://stephenlu.iteye.com/blog/2066922"
---

**前言**

> 功能需要我们调用大量的Ajax ，怎么才能有效率地实现？在Java Web开发中，我通常使用Spring + jQuery .
> 
> 但是jQuery 的ajax方法相比于DWR，个人认为DWR更能快捷地开发。

**一、代码比较**

举个例子：异步得到一个实体类

jQuery 实现：

> Java:
> 
> ```
> 	@RequestMapping("/getEntity")
	public String getEntity()
	{
		return "stephen";
	}
> ```

> JS:
> 
> ```
> $.ajax({
      url:"/getEntity",
      success:function (data){
              alert(data);
      }
});
> ```

DWR实现：

> Java:
> 
> ```
> @RemoteProxy(name = "personController")
public class PersonController {

	@RemoteMethod
	public String getEntity() {
             return "stephen";
	}

}
> ```

> JS：
> 
> ```
>     personController.getEntity(callBack);

    function callBack(data){ 
      
         alert(data);  
    }
> ```

**二、DWR 的优势**

> **便捷：**上面的代码量比较似乎微乎其微，但一旦上了一个数量级就不同了；比如要写10个功能，jQuery就要做10次url映射，而DWR只是在写好Java代码后直接在JS调用这些方法,personController.xxx ,回调函数的参数接受后台的返回值。
> 
> **形象：**JS调用写好的Java代码 （形式上），使得浏览器跟服务器端的交互关系变得非常强，便于理解。

**三、如何使用DWR**

> 官网：[http://directwebremoting.org](http://directwebremoting.org)
> 
> 如何使用，前人已经写过很多这样的帖子了， 感谢···
> 
> 1）配置文件方式：
> 
> [http://jc-dreaming.iteye.com/blog/564848](http://jc-dreaming.iteye.com/blog/564848)
> 
> 我的一个Myeclipse小例子，已测试通过：[http://pan.baidu.com/s/11PDAZ](http://pan.baidu.com/s/11PDAZ)
> 
> 2）Spring集成
> 
> [http://blog.csdn.net/geloin/article/details/7537148](http://blog.csdn.net/geloin/article/details/7537148)
> 
> Myeclipse小例子 :[http://pan.baidu.com/s/1mqB49](http://pan.baidu.com/s/1mqB49)

**四、对DWR的理解**

> 官方给出的特征是：DWR is a RPC library which makes it easy to call Java functions from JavaScript and to call JavaScript functions from Java
> 
> 它可以允许在浏览器里的代码使用运行在WEB服务器上的JAVA函数，就像它就在浏览器里一样。就是说：JS调用写好的Java代码。
> 
> 反向Ajax，Java代码调用js函数。