Vaadin 7:从服务器到客户端的RPC调用

时间:2014-08-06 09:22:32

标签: vaadin vaadin7

我想创建自定义图像组件。所以我从Integrating with Server-side开始一步一步地进行操作。对于基本步骤或第一步,我为测试 Server to Client RPC call 创建了以下步骤。

MyComponentWidget.java

public class MyComponentWidget extends HTML {

public MyComponentWidget() {
    getElement().setAttribute("class", "thumbnail");
}

public final void createCustomImage(final String url) {
 getElement().setInnerHTML("<div class='delete-block'></div><img src=" + url + " />");
}
}

MyComponentState.java

public class MyComponentState extends AbstractComponentState {
private String url;
private String html;

public final String getUrl() {
    return url;
}

public final void setUrl(final String url) {
    this.url = url;
}

public final String getHtml() {
    return html;
}

public final void setHtml(final String html) {
    this.html = html;
}
}

MyComponentConnector.java

public class MyComponentConnector extends AbstractComponentConnector {

public MyComponentConnector() {
    registerRpc(MyComponentClientRpc.class, new MyComponentClientRpc() {

        @Override
        public void getMessage() {
            // never reach to this place
            System.err.println("Reach Here !");
            getState().setHtml(getWidget().getHTML());
        }
    });
}

@Override
public final MyComponentWidget getWidget() {
    return (MyComponentWidget) super.getWidget();
}

@Override
public final MyComponentState getState() {
    return (MyComponentState) super.getState();
}

@OnStateChange("url")
final void updateText() {
    getWidget().createCustomImage(getState().getUrl());
}
}

MyComponentClientRpc.java

import com.vaadin.shared.communication.ClientRpc;
public interface MyComponentClientRpc extends ClientRpc {
void getMessage();
}

MyComponent.java

public class MyComponent extends AbstractComponent {

public MyComponent(final String url) {
    getState().setUrl(url);
}

public final MyComponentState getState() {
    return (MyComponentState) super.getState();
}

public final String getHTML() {
    getRpcProxy(MyComponentClientRpc.class).getMessage();
    return getState().getHtml();
}
}

并致电

MyComponent image = new MyComponent("myImageUrl");
System.out.println(image.getHTML());

我的问题是为什么我总是在我的控制台上获得 null 值?我可以在浏览器中看到图像,但 System.out.println(image.getHTML()); 会生成 null 。我错过了什么?

1 个答案:

答案 0 :(得分:-1)

要从客户端到服务器进行rpc调用,必须扩展ServerRpc接口,例如:

package com.example.client.MyServerRpc

public interface MyServerRpc extends com.vaadin.shared.communication.ServerRpc {
    void sendHTML(String html);
}

在您的连接器中注册rpc:

private MyServerRpc rpc = RpcProxy.create(MyServerRpc.class, this);

然后您可以使用连接器中注册的rpc发送值:

 rpc.sendHTML(html);

要在组件或分机的服务器端类上接收值,您必须创建rpc接口的实例:

private MyServerRpc rpc = new MyServerRpc() {
    @Override
    public void sendHTML(String html) {
        // this method will be called!
    }

};

并在构造函数中注册:

registerRpc(rpc);

执行这些步骤之后,从客户端到服务器的RPC应该可以正常工作。