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
  2. SparkJavaAjaxSample.java
  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:
Root
|---build.gradle
|
└───src
    └───main
        ├───java
        │   └───com.firstfewlines
        │           SparkJavaAjaxSample.java
        │
        └───resources
            └───public
                │   index.html
                │
                └───js
                        ajax.js


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 {
    mavenCentral()
}

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.


2. SparkJavaAjaxSample.java
package com.firstfewlines;
import static spark.Spark.*;
import spark.QueryParamsMap;

public class SparkJavaAjaxSample {

    public static void main(String [] argv){

        staticFiles.location("/public");

        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">
<head>
    <meta charset="UTF-8">
    <title>FirstFewLines.com - SparkJava example with JQuery Ajax</title>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"
            integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
            crossorigin="anonymous"></script>

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


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

    $.ajax({
      url: '/api/sum?a=' + a + '&b='+b,
      success: function(data) {
        $('#result').text(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.

output:
:compileJava
:processResources
:classes
:run
[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 0.0.0.0:4567
[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]}{0.0.0.0:4567}
[Thread-0] INFO org.eclipse.jetty.server.Server - Started @247ms
> Building 75% > :run


References:


Download source code:


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