gwt实现基于spring的json应用实例

在这里写了一个实例,我管它叫“武器列表”。仿google GWT的mvp示例写的,它的示例是为了演示MVP开发模式写的,见:

http://code.google.com/p/gwt-mvp-sample/

但是这个示例使用的是rpc方式和服务器通信。我们使用spring 3.0和json通信。

因此参照它写了个简单的实例,主要是解释json数据如何发送和如何获取。另外,临摹了一下,体会mvp模式。

spring的json返回视图,默认情况下将ModelMap中的所有对象都转化了,而实际上客户端只需要其中的某个对象。

这需要这样,比如:

@RequestMapping(“/list.json”)
@ModelAttribute(“data”)
public List list() {
return data;
}

这里使用了ModelAttribute注解,这样只返回名为data的对象,在这里是个List,样子大概是这样:

{“data”:[{"name":"w1","id":"1","description":"w1.desc","imageUrl":"w1.png"},{"name":"w2","id":"2","description":"w2.desc","imageUrl":"w2.png"}]}

一个名为data的数组。

那么,在gwt的客户端,我只想要这个数组,而不是带data属性的对象,怎么办呢?见Weapon代码,用于表示客户端的模型:

package com.easymorse.weapons.client.model;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;

public class Weapon extends JavaScriptObject {

protected Weapon() {
}

public final native String getId() /*-{
return this.id;
}-*/;

public final native void setId(String id) /*-{
this.id = id;
}-*/;

public final native String getName() /*-{
return this.name;
}-*/;

public final native void setName(String name) /*-{
this.name = name;
}-*/;

public final native String getDescription() /*-{
return this.description;
}-*/;

public final native void setDescription(String description) /*-{
this.description = description;
}-*/;

public final native String getImageUrl() /*-{
return this.imageUrl;
}-*/;

public final native void setImageUrl(String imageUrl) /*-{
this.imageUrl = imageUrl;
}-*/;

public static native JsArray<Weapon> arrayFromJson(String jsonString) /*-{
return eval(‘(‘ + jsonString + ‘)’).data;
}-*/;
}

这里在eval方法执行后,加.data,表示只取data属性的内容,也即数组。当然数组的格式是JsArray而不是java的List啥的了。

其他部分,使用了MVP模式,但是还不完全,因为没有事件处理部分。在后续实例中逐渐加上。

源代码见:

http://easymorse.googlecode.com/svn/tags/Weapons-0.1

創建PDF格式    发送文章为PDF   

这篇文章上的评论的 RSS feed TrackBack URI

Leave a Reply