Calling a JAVA method through JavaScript in SAPUI5 project

Create a REST service hosted on a server and place java method inside it. Now you can call this REST service from a SAPUI5 application using AJAX by passing required parameters.

Understanding the Architecture

In SAPUI5, you cannot directly call Java methods from JavaScript. Instead, you need to expose your Java functionality through a REST API that acts as a bridge between your frontend SAPUI5 application and backend Java services.

SAPUI5 App REST Service Java Method AJAX Calls

Implementation Steps

Step 1: Create Java REST Service

First, create a Java REST service using JAX-RS annotations ?

@Path("/api")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class UserService {
    
    @GET
    @Path("/users/{id}")
    public Response getUserById(@PathParam("id") int userId) {
        // Your Java method logic here
        User user = getUserFromDatabase(userId);
        return Response.ok(user).build();
    }
    
    @POST
    @Path("/users")
    public Response createUser(User user) {
        // Your Java method logic here
        User createdUser = saveUserToDatabase(user);
        return Response.status(201).entity(createdUser).build();
    }
}

Step 2: Call REST Service from SAPUI5

In your SAPUI5 controller, use jQuery.ajax() to call the Java REST service ?

// GET request to fetch user data
onGetUser: function() {
    var userId = 123;
    jQuery.ajax({
        url: "http://localhost:8080/api/users/" + userId,
        type: "GET",
        dataType: "json",
        success: function(data) {
            // Handle successful response
            console.log("User data:", data);
            this.getView().getModel().setData(data);
        }.bind(this),
        error: function(xhr, status, error) {
            // Handle error
            console.error("Error:", error);
            sap.m.MessageToast.show("Failed to fetch user data");
        }
    });
},

// POST request to create new user
onCreateUser: function() {
    var userData = {
        name: "John Doe",
        email: "john@example.com"
    };
    
    jQuery.ajax({
        url: "http://localhost:8080/api/users",
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify(userData),
        success: function(response) {
            sap.m.MessageToast.show("User created successfully");
        },
        error: function(xhr, status, error) {
            sap.m.MessageToast.show("Failed to create user");
        }
    });
}

Conclusion

By creating a REST API wrapper around your Java methods, you can effectively call Java functionality from SAPUI5 applications using standard AJAX requests, enabling seamless integration between frontend and backend components.

Updated on: 2026-03-13T18:01:48+05:30

274 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements