How to call a Java function inside JavaScript Function?

JavaScript cannot directly call Java methods since Java runs on the server while JavaScript runs in the browser. You need to use a server-side framework like JSP or create REST endpoints to bridge this communication.

Method 1: Using JSP with AJAX

This approach uses AJAX to make HTTP requests to JSP pages that execute Java code.

JavaScript Code

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// JavaScript function to call Java method via JSP
function callJavaFunction() {
    $.ajax({
        url: '/project/myexecution.jsp',
        type: 'GET',
        success: function(response) {
            console.log('Java function executed successfully');
            console.log('Response:', response);
        },
        error: function(xhr, status, error) {
            console.error('Error calling Java function:', error);
        }
    });
}

// Call the function when document is ready
$(document).ready(function() {
    $('#callJavaBtn').click(callJavaFunction);
});
</script>

<button id="callJavaBtn">Call Java Function</button>
<div id="result"></div>

JSP Code (myexecution.jsp)

<%@ page import="com.example.DeleteConfig" %>
<%@ page contentType="application/json" %>
<%
    try {
        // Call your Java method
        DeleteConfig.initiate();
        
        // Return success response
        response.getWriter().write("{"status": "success", "message": "Java function executed"}");
    } catch (Exception e) {
        // Return error response
        response.getWriter().write("{"status": "error", "message": "" + e.getMessage() + ""}");
    }
%>

Method 2: Using REST API with Servlets

A more modern approach using servlets to create REST endpoints.

JavaScript Code

<script>
async function callJavaViaREST() {
    try {
        const response = await fetch('/project/api/execute', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                action: 'initiate',
                parameters: {}
            })
        });
        
        const result = await response.json();
        console.log('Java function result:', result);
        
        document.getElementById('result').innerHTML = 
            `<p>Status: ${result.status}</p><p>Message: ${result.message}</p>`;
    } catch (error) {
        console.error('Error:', error);
    }
}

document.getElementById('callRestBtn').addEventListener('click', callJavaViaREST);
</script>

<button id="callRestBtn">Call Java via REST</button>
<div id="result"></div>

Comparison

Method Complexity Maintainability Best For
JSP with AJAX Low Medium Simple applications
REST API with Servlets Medium High Modern web applications

Key Points

  • JavaScript runs in the browser, Java runs on the server
  • HTTP requests bridge the communication gap
  • Always handle errors in AJAX calls
  • Use JSON for structured data exchange
  • Consider security implications when exposing Java methods

Conclusion

Use AJAX requests to JSP pages or REST endpoints to call Java functions from JavaScript. The REST approach is more maintainable for modern applications, while JSP works well for simple use cases.

Updated on: 2026-03-15T22:12:31+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements