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:
 1Root
 2|---build.gradle
 3|
 4└───src
 5    └───main
 6        ├───java
 7        │   └───com.firstfewlines
 8        │           SparkJavaAjaxSample.java
 910        └───resources
11            └───public
12                │   index.html
1314                └───js
15                        ajax.js
16

Now let us see the content of the files:

1. build.gradle
 1apply plugin: 'application'
 2apply plugin: 'java'
 3apply plugin: 'idea'
 4
 5mainClassName = 'com.firstfewlines.SparkJavaAjaxSample'
 6
 7repositories {
 8    mavenCentral()
 9}
10
11dependencies {
12    compile 'com.sparkjava:spark-core:2.6.0'
13    compile 'org.slf4j:slf4j-simple:1.7.25'
14}

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


2. SparkJavaAjaxSample.java
 1package com.firstfewlines;
 2import static spark.Spark.*;
 3import spark.QueryParamsMap;
 4
 5public class SparkJavaAjaxSample {
 6
 7    public static void main(String [] argv){
 8
 9        staticFiles.location("/public");
10
11        get("/api/sum", (req, res) -> {
12            QueryParamsMap map = req.queryMap();
13            try {
14                Integer a = map.get("a").integerValue();
15                Integer b = map.get("b").integerValue();
16                return a + b;
17            }
18            catch (Exception e){
19                return "Error: " + e.getMessage();
20            }
21        });
22    }
23}
24

3. index.html
 1<!DOCTYPE html>
 2<html lang="en">
 3<head>
 4    <meta charset="UTF-8">
 5    <title>FirstFewLines.com - SparkJava example with JQuery Ajax</title>
 6    <script src="https://code.jquery.com/jquery-3.2.1.min.js"
 7            integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
 8            crossorigin="anonymous"></script>
 9
10    <script src="/js/ajax.js" type="text/javascript"></script>
11</head>
12<body>
13<h2>FirstFewLines.com - SparkJava example with JQuery Ajax</h2>
14<hr>
15<div style="display:block">
16    <form>
17        <label for="a">Number 1:</label>
18        <input type="number" id="a"/>
19        <br>
20        <label for="a">Number 2:</label>
21        <input type="number" id="b"/>
22        <br>
23        <input type="button" id="buttonSum" value="Sum"/>
24        <br>
25        <p>Result:&nbsp;:<span id="result"></span></p>
26    </form>
27</div>
28</body>
29</html>

4. ajax.js
 1$(function() {
 2  $('#buttonSum').click(function(){
 3    var a = $('#a').val();
 4    var b = $('#b').val();
 5
 6    $.ajax({
 7      url: '/api/sum?a=' + a + '&b='+b,
 8      success: function(data) {
 9        $('#result').text(data);
10      }
11    });
12  });
13});
14

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:
 1:compileJava
 2:processResources
 3:classes
 4:run
 5[main] INFO spark.staticfiles.StaticFilesConfiguration - StaticResourceHandler configured with folder = /public
 6[Thread-0] INFO org.eclipse.jetty.util.log - Logging initialized @152ms to org.eclipse.jetty.util.log.Slf4jLog
 7[Thread-0] INFO spark.embeddedserver.jetty.EmbeddedJettyServer - == Spark has ignited ...
 8[Thread-0] INFO spark.embeddedserver.jetty.EmbeddedJettyServer - >> Listening on 0.0.0.0:4567
 9[Thread-0] INFO org.eclipse.jetty.server.Server - jetty-9.4.4.v20170414
10[Thread-0] INFO org.eclipse.jetty.server.session - DefaultSessionIdManager workerName=node0
11[Thread-0] INFO org.eclipse.jetty.server.session - No SessionScavenger set, using defaults
12[Thread-0] INFO org.eclipse.jetty.server.session - Scavenging every 600000ms
13[Thread-0] INFO org.eclipse.jetty.server.AbstractConnector - Started ServerConnector@765a6eec{HTTP/1.1,[http/1.1]}{0.0.0.0:4567}
14[Thread-0] INFO org.eclipse.jetty.server.Server - Started @247ms
15> Building 75% > :run
16

References:


Download source code:


comments powered by Disqus