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 Developer Relations Engineer at MariaDB. He has been programming computers since the mid-90s. Starting with BASIC, Alejandro transitioned to C, C++, and Java during his academic years at the National University of Colombia. He relocated first to the UK and then to Finland to foster his involvement in the open-source industry. Alejandro is a recognized figure in Java and MariaDB circles.

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
An excerpt from Chapter 9 of my book on implementing infinite lazy loading in Vaadin.
Hello, World in Vaadin 10+
·1243 words·6 mins
Vaadin
A guide to creating a Hello, World application using Vaadin 10+ and Java.
Data-Centric Applications with Vaadin 10?
·242 words·2 mins
Vaadin News
Migrating the examples from my Vaadin 8 book to Vaadin 10.