How to call a Java method from a JavaScript function in the browser

In this video I demonstrate how to call a Java method that runs in the server from a JavaScript function running in the web browser:






In short, you need a Java web application with the Vaadin dependencies (you can quickly create one here), a script file in the webapp/frontend/ directory and a Java class with a method annotated with @ClientCallable that sends an Element to the JavaScript function. The JavaScript function can use the $server object in the Element instance to call the annotated Java method.

Here's the code:

MainView.java:

@JavaScript("frontend://script.js")
@Route
public class MainView extends Div {
    public MainView() {
        getElement().executeJavaScript(
                "someJavaScriptFunction($0)", getElement());
    }

    @ClientCallable

    public someJavaMethod(String message) {
        System.out.println(message);
    }
}

script.js:

function someJavaScriptFunction(element) {
    element.$server.someJavaMethod("Hello server!");
}

You can read the full step-by-step tutorial here.

Comments

Popular posts from this blog

Infinite lazy loading

Hello, World in Vaadin 10+

Semantic coupling