Skip to main content

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

·128 words·1 min
Programming Vaadin
Alejandro Duarte
Author
Alejandro Duarte
Alejandro Duarte is a Software Engineer, published author, and award winner. He currently works for MariaDB plc as a Developer Relations Engineer. Starting his coding journey at 13 with BASIC on a rudimentary black screen, Alejandro quickly transitioned to C, C++, and Java during his academic years at the National University of Colombia. Relocating first to the UK and then to Finland, Alejandro deepened his involvement in the open-source community. He’s a recognized figure in Java circles, credited with articles and videos amassing millions of views, and presentations at international events.

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.

Enjoyed this post? I can help your team implement similar solutions—contact me to learn more.

Related

Infinite lazy loading
·269 words·2 mins
Vaadin
Here’s a short excerpt of Chapter 9 Lazy Loading of my book Data-Centric Applications with Vaadin 8.
Hello, World in Vaadin 10+
·1243 words·6 mins
Vaadin
Vaadin is a set of tools to create web applications tailored to both, client-side and server-side developers.
Data-Centric Applications with Vaadin 10?
·242 words·2 mins
Vaadin News
I recently got some hard copies of my last book about Vaadin.