Spark Java example with AJAX JQuery

Spark is a relatively new, simple and lightweight framework written in Java which helps developers to rapidly create web services in minimal effort. It comes with embedded Jetty web server which hosts the web services. The syntax of declaring web services are very simple, quite similar with Node.js, which makes Node.js developers learn SparkJava quickly.

Spark framework only works on Java 8 as it is built on Java 8’s Lambda philosophy.

Here I have written a simple example of implementing Ajax call using JQuery where the server side API is provided by Spark. In this example we will get input of two numbers from the web page UI, make a ajax call to server with those numbers, the numbers get added at the server and returned result and finally display the result to web page UI without refreshing the page.

There are only four files in this example:

  1. build.gradle
  3. index.html
  4. ajax.js

The index.html also refer to the JQuery library javascript through CDN. So, make sure you have live internet connection while running the sample.

The files are placed as per following folder structure:
        │   └───com.firstfewlines
                │   index.html

Now let us see the content of the files:

1. build.gradle
apply plugin: 'application'
apply plugin: 'java'
apply plugin: 'idea'

mainClassName = 'com.firstfewlines.SparkJavaAjaxSample'

repositories {

dependencies {
    compile 'com.sparkjava:spark-core:2.6.0'
    compile 'org.slf4j:slf4j-simple:1.7.25'

We are including slf4j-simple library to enable the logging messages to be displayed to the console.

package com.firstfewlines;
import static spark.Spark.*;
import spark.QueryParamsMap;

public class SparkJavaAjaxSample {

    public static void main(String [] argv){


        get("/api/sum", (req, res) -> {
            QueryParamsMap map = req.queryMap();
            try {
                Integer a = map.get("a").integerValue();
                Integer b = map.get("b").integerValue();
                return a + b;
            catch (Exception e){
                return "Error: " + e.getMessage();

3. index.html
<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title> - SparkJava example with JQuery Ajax</title>
    <script src=""

    <script src="/js/ajax.js" type="text/javascript"></script>
<h2> - SparkJava example with JQuery Ajax</h2>
<div style="display:block">
        <label for="a">Number 1:</label>
        <input type="number" id="a"/>
        <label for="a">Number 2:</label>
        <input type="number" id="b"/>
        <input type="button" id="buttonSum" value="Sum"/>
        <p>Result:&nbsp;:<span id="result"></span></p>

4. ajax.js
$(function() {
    var a = $('#a').val();
    var b = $('#b').val();

      url: '/api/sum?a=' + a + '&b='+b,
      success: function(data) {

How to run?

  • Make sure you have latest version of Gradle installed and PATH is configured.
  • Go to the directory where you unzipped the file i.e. where the build.gradle is there
  • Run gradle run command
  • This should run the application with output similar to below
  • Now open your browser and point to http://localhost:4567/

Alternatively, you can use IntelliJ IDEa or Eclipse to import the Gradle project and run from there.

[main] INFO spark.staticfiles.StaticFilesConfiguration - StaticResourceHandler configured with folder = /public
[Thread-0] INFO org.eclipse.jetty.util.log - Logging initialized @152ms to org.eclipse.jetty.util.log.Slf4jLog
[Thread-0] INFO spark.embeddedserver.jetty.EmbeddedJettyServer - == Spark has ignited ...
[Thread-0] INFO spark.embeddedserver.jetty.EmbeddedJettyServer - >> Listening on
[Thread-0] INFO org.eclipse.jetty.server.Server - jetty-9.4.4.v20170414
[Thread-0] INFO org.eclipse.jetty.server.session - DefaultSessionIdManager workerName=node0
[Thread-0] INFO org.eclipse.jetty.server.session - No SessionScavenger set, using defaults
[Thread-0] INFO org.eclipse.jetty.server.session - Scavenging every 600000ms
[Thread-0] INFO org.eclipse.jetty.server.AbstractConnector - Started ServerConnector@765a6eec{HTTP/1.1,[http/1.1]}{}
[Thread-0] INFO org.eclipse.jetty.server.Server - Started @247ms
> Building 75% > :run


Download source code:

Hansaraj avatar
About Hansaraj
Hansaraj is a Software Engineer experienced in Java, Groovy, JavaScript, SQL, C#, C++
comments powered by Disqus