Spark Java AJAX post example using JQuery

This post is very similar with the Spark Java example with JQuery Ajax except here we would use POST method for the Ajax call.

Like the other example, we would get input of two numbers from the web page UI, make a ajax POST 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.

The main challenge here is, it is difficult to automatically parse the post data by Spark framework, at least in current version (2.6.0). I am using Apache HttpClient library - URLEncodedUtils class to parse the post data.

Now let us see the coding part.

Like the other example, here also only four files needed:

  1. build.gradle
  2. index.html
  3. ajax.js
  4. SparkJavaAjaxPostSample.java

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
        │           SparkJavaAjaxPostSample.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.SparkJavaAjaxPostSample'

repositories {
    mavenCentral()
}

dependencies {
    compile 'com.sparkjava:spark-core:2.6.0'
    compile 'org.slf4j:slf4j-simple:1.7.25'
    compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.3'
}

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

2. index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>FirstFewLines.com - SparkJava Ajax post example using JQuery</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 Ajax post example using JQuery</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>


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

    var data = {'a': a, 'b': b};

    $.ajax({
      method: 'POST',
      data: data,
      url: '/api/sum',
      success: function(data) {
        $('#result').text(data);
      }
    });
  });
});

Here you can see, I am passing JSON data to the server. It is also possible to pass the form data. In that case the server side parsing logic needs to be changed.


4. SparkJavaAjaxPostSample.java

Now let us see the server side parsing logic to parse the data. The data arrives to server is something like: “a=4&b=5” and available through request body. (assuming 4 & 5 are the inputs by user).

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

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SparkJavaAjaxPostSample {

    public static void main(String [] argv){

        staticFiles.location("/public");

        post("/api/sum", (req, res) -> {

            List<NameValuePair> pairs = URLEncodedUtils.parse(req.body(), Charset.defaultCharset());

            Map<String, String> params = toMap(pairs);

            try {
                Integer a = Integer.parseInt(params.get("a"));
                Integer b = Integer.parseInt(params.get("b"));
                return a + b;
            }
            catch (Exception e){
                return "Error: " + e.getMessage();
            }
        });
    }

    private static Map<String, String> toMap(List<NameValuePair> pairs){
        Map<String, String> map = new HashMap<>();
        for(int i=0; i<pairs.size(); i++){
            NameValuePair pair = pairs.get(i);
            map.put(pair.getName(), pair.getValue());
        }
        return map;
    }
}


How to run the Spark Java application?

  • 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:
Starting a Gradle Daemon (subsequent builds will be faster)
:clean
:compileJava
:processResources
:classes
:run
[main] INFO spark.staticfiles.StaticFilesConfiguration - StaticResourceHandler configured with folder = /public
[Thread-0] INFO org.eclipse.jetty.util.log - Logging initialized @162ms 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@6cbfdcfe{HTTP/1.1,[http/1.1]}{0.0.0.0:4567}
[Thread-0] INFO org.eclipse.jetty.server.Server - Started @254ms


References:


Download the source code:


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