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.
Programming
January 24, 2019
0

Search

Popular Posts

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 f…

Testing MariaDB ColumnStore performance

MariaDB 's ColumnStore is an engine that stores data in a columnar fashion…

New book - Practical Vaadin: Developing Web Applications in Java

I'm glad to announce the availability of my most recent book, Practical Vaa…

Recent Comments

Contact Me