The following basic types are supported on the Java side. These types are automatically converted to strings or numbers in the Javascript side.
- String
- Integer and int
- Double and double
- Float and float
- BigDecimal
Here are a couple of example Java service methods from Samples/src/main/java/com/lambdazen/websocket/sample/CallTestService.java:
public void testSimpleTypes(String s, Integer i, BigDecimal bd, Double d, Float f) { ... } public void testUnboxedTypes(int i, double d, float f) { ... }
You can also pass arrays (and arrays of arrays) of the above types from Javascript to Java. Calls from Java to Javascript must be only on boxed types (Integer not int).
public void testArrays(String[] s, int[] i, BigDecimal[] bd, double[] d, Float[] f)
The JsonNode
class from Jackson can be used to encapsulate Javascript objects as they are passed from Javascript to Java or vice versa. In the following example from CallTestService, any Javascript object passed to testJSONNode
is sent back as the second argument of the append
method in the callback object.
public void testJSONNode(JsonNode jn) { try { rws.call("append", "testJSONNodes", jn); } catch (RMIWebSocketException e) { e.printStackTrace(); } }
Any Javascript object can be converted to a Map using Jackon's Raw Data Binding approach.
public void testMap(Map m) { ... }
Any Javascript object can be converted to a POJO using Jackon's Full Data Binding approach. Here is an example from CallTestService.java
:
public void testMapper(Pojo p) { try { rws.call("append", "testMapper", p.toString()); } catch (RMIWebSocketException e) { e.printStackTrace(); } } public static class Pojo { String id; int[] intArray; Mojo m; public void setMojo(Mojo x) { m = x; } public void setId(String x) { id = x; } public void setIntArray(int[] x) { intArray = x; } public String toString() { return "Pojo(id=" + id + ", int[]=" + Arrays.asList(ArrayUtils.toObject(intArray)) + ", mojo=" + m + ")"; } } public static class Mojo { int level; public void setLevel(int x) { level = x; } public String toString() { return "Mojo(" + level + ")"; } }
The client side code in calltest.jsp
invokes this as:
rws.call("testMapper", {"id": "myID", "intArray": [1, 2, 3], "mojo": {"level": 8}});
Note: The available methods are defined by the names of the getters and setters, not the names of the member variables.