Server
在客户端可以用JavaScript访问的方法必须用@ExtDirectMethod注释。注释方法的bean必须是Spring管理的bean。
@Service
public class TestAction {
@ExtDirectMethod
public String doEcho(String message) {
return message;
}
@ExtDirectMethod
public int anotherAction() {
return 1;
}
}
如果方法需要访问服务器对象,如请求和响应,添加参数的方法签名。
@ExtDirectMethod
public String doEcho(String message, HttpServletRequest request) {
//do something with the request
return message;
}
ExtDirectSpring支持的服务器对象参数:
HttpServletResponse
HttpServletRequest
HttpSession
Locale
Principal
Parameters annotated with @RequestHeader (since 1.1.0)
服务器对象参数可以添加任意顺序
@ExtDirectMethod
public String doSomething(HttpServletResponse response, int fromClient1,
HttpServletRequest request, int fromClient2,
Locale locale, int fromClient3) {
//do something here
}
客户端方法看不到服务器对象参数,调用doSomething方法示例如:testAction.doSomething(1, 2, 3, callback)。
类库也支持 @DateTimeFormat和@NumberFormat注释。
@ExtDirectMethod
public Map<String, Object> aMethod(@DateTimeFormat(iso = ISO.DATE_TIME) Date aDate,
@NumberFormat(style = NumberFormat.Style.PERCENT) BigDecimal percent) {
...
}
Client
Spring bean的name是客户端action的名字。如testAction.doEcho('ping', callback)将会调用服务器端Spring bean testAction的方法doEcho。调用服务器的方法通常是异步因此需要一个回调函数,回调函数将会被调用有返回的时候。回调函数是调用服务器方法的最一个参数。如果服务器方法一个参数没有,回调函数是唯一参数。testAction.anotherAction(callback)。最后一个参数也有可能是回调函数执行的作用域,testAction.doSomething(1, 2, 3, callback, this)。
参数的顺序和个数必须跟服务器方法签名一致(服务器对象除外)。
回调函数不是必须的可以省略。
Callback function
var callback = function(result, e) {
// do something with the result
};
回调函数会被调用当服务器端返回结果或抛出一个异常。一个Ext.Direct回调函数被调用,带有两个参数:
result 这个参数包含服务器方法返回的数据。
e 一个Ext.Direct.RemotingEvent (Ext JS 3) 或 Ext.direct.RemotingEvent (Ext JS 4.x and Sencha Touch 2)
event对象有一些有用的属性和方法:
status true 如果方法调用成功,false如果方法调用失败
result 包含同返回结果一样数据
type rpc或exception 如果异常发生
action bean的name例如‘testAction’
method 方法的名字 (*'doEcho'*)
tid 事务id
getTransaction() 获得调用服务器方法的事务。这个对象包含一些信息,如transaction.args包含方法调用时的参数。
Events
Direct Manager支持两类事件event和exception。event在调用服务器方法返回后触发。exception在发生异常时触发。可以很容易监听这些事件通过添加监听到Ext.direct.Manager。
//Ext JS 4.x and Sencha Touch 2
Ext.direct.Manager.on('event', function(e) {
//do something here
});
Ext.direct.Manager.on('exception', function(e) {
//do something here
});
Examples
- http://demo.rasc.ch/eds/extjs3/simple.html
- http://demo.rasc.ch/eds/extjs3/direct.html
- http://demo.rasc.ch/eds/extjs41/direct.html
- http://demo.rasc.ch/eds/extjs42/direct.html