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

What is a Database Proxy?

A proxy is a server software, typically installed in a separate machine, that …

ChatGPT as a MariaDB database

ChatGPT is truly impressive. You can instruct it to do all sorts of things whe…

Building a Kubernetes cluster on Raspberry Pi (with automation)

Some months ago, I was lucky enough to get a bunch of Raspberry Pi minicompute…

Recent Comments

Contact Me