webfirmframework for Java Experts
Custom Server Method
The aim of custom server method is to declare a custom method in the server which can be called from the client using JavaScript.
browserPage.addServerMethod(methodName, serverAsyncMethod);
addServerMethod
of BrowserPage
can be used to register a custom server method. The custom server method can be called from JavaScript code. See the below sample
ServerAsyncMethod serverAsyncMethod = new ServerAsyncMethod() {
@Override
public WffBMObject asyncMethod(WffBMObject wffBMObject,
Event event) {
//will print 'some value'
System.out.println(wffBMObject.get("somekeyFromClient").getValue());
//prints the type of value
System.out.println(wffBMObject.get("somekeyFromClient").getValueType());
String serverMethodName = event.getServerMethodName();
//will print someUniqueMethodName
System.out.println(serverMethodName);
// used to send data to the client
WffBMObject bmObject = new WffBMObject();
bmObject.put("someKey", BMValueType.STRING,
"こんにちは Web Firm Framework");
bmObject.put("testFun", BMValueType.FUNCTION, "function(arg) {alert(arg);}");
return bmObject;
}
};
browserPage.addServerMethod("someUniqueMethodName", serverAsyncMethod);
Invoke the server method from JavaScript, see the code
var arguments = {
'somekeyFromClient' : 'some value',
'numb' : 55555,
'bool' : true,
'anObj' : {
'key' : 'val'
},
'funcArray' : function() {console.log('m function');},
'numberArray' : [ 5, 55, 555, 55, 5555 ]
};
var callbackFunction = function(obj) {
console.log('callback obj ', obj);
for (key in obj) {
console.log('key is ' + key, obj[key]);
}
obj.testFun('check out browser console to see values received from server');
};
wffAsync.serverMethod('someUniqueMethodName', arguments).invoke(callbackFunction);
The first argument passed in
wffAsync.serverMethod
is the name of the method to be called.
The second argument
arguments
passed in
wffAsync.serverMethod
will be received as a
wffBMObject
argument in
asyncMethod
method. The JavaScript object
arguments
can also contain
Int8Array
value type to pass binary data, which will be received in
wffBMObject
as a value type of
BMValueType.BM_BYTE_ARRAY
i.e. the value is a class type of
WffBMByteArray
which contains bytes.
The
callbackFunction
function will be called for the result of
asyncMethod
server method. The argument
obj
in
callbackFunction
is conventional JavaScript object of
bmObject
returned by
asyncMethod
in the server.
The server method can also send binary data using
WffBMByteArray
. Check out
BMValueType
enum to know the supported data types of value to send from server to client
and vice versa.
In the above JavaScript code,
arguments
,
callbackFunction
and
obj
are optional arguments.