準備技術:
Client Widget與 Server Component溝通仰賴RPC,一般用於stateless 事件(參考Vaadin 事件處理)的使用,和Shared state的事件不同,RPC有Server端方法,也有Client方法。
建立Server-Client RPC方法:
程式展示:
一個元件要使用RPC,先註冊。
public class MyComponent extends AbstractComponent {
public MyComponent() {
registerRpc(new MyComponentServerRpc() {
@Override
public void clicked(String buttonName) {
Notification.show("You clicked, so I made an RPC to the server.");
}
});
}
Server端的RPC。
public interface MyComponentServerRpc extends ServerRpc {
public void clicked(String buttonName);
}
Client的RPC
public interface MyComponentClientRpc extends ClientRpc {
// TODO example API
public void alert(String message);
}
中間設個Connector。
@Connect(MyComponent.class)
public class MyComponentConnector extends AbstractComponentConnector {
private static final long serialVersionUID = 5953609150057019293L;
public MyComponentConnector() {
registerRpc(MyComponentClientRpc.class, new MyComponentClientRpc() {
private static final long serialVersionUID = -1056192951789062628L;
public void alert(String message) {
// TODO Do something useful
Window.alert(message);
}
});
// TODO ServerRpc usage example, do something useful instead
getWidget().addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
final MouseEventDetails mouseDetails = MouseEventDetailsBuilder
.buildMouseEventDetails(event.getNativeEvent(),
getWidget().getElement());
MyComponentServerRpc rpc =
getRpcProxy(MyComponentServerRpc.class);
rpc.clicked(mouseDetails.getButtonName());
}
});
}
@Override
protected Widget createWidget() {
return GWT.create(MyComponentWidget.class);
}
@Override
public MyComponentWidget getWidget() {
return (MyComponentWidget) super.getWidget();
}
@Override
public MyComponentState getState() {
return (MyComponentState) super.getState();
}
@OnStateChange("text")
void updateText() {
getWidget().setText(getState().text);
}
@Override
public void onStateChanged(StateChangeEvent stateChangeEvent) {
super.onStateChanged(stateChangeEvent);
// TODO do something useful
final String text = getState().text;
getWidget().setText(text);
// Set a resource
getWidget().setMyIcon(getResourceUrl("myIcon"));
}
}
UI主程式
public class VaadinrpceventUI extends UI {
@WebServlet(value = "/*", asyncSupported = true)
@VaadinServletConfiguration(productionMode = false, ui = VaadinrpceventUI.class)
public static class Servlet extends VaadinServlet {
}
@Override
protected void init(VaadinRequest request) {
MyComponent mycomponent=new MyComponent();
VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
layout.addComponent(mycomponent);
}
}
執行的時候,發現Vaadin7.3需要第三方Lib, 所以無法顯示,改進中
參考資料:
Day 28 結束