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:
 1Root
 2|---build.gradle
 3|
 4└───src
 5    └───main
 6        ├───java
 7        │   └───com.firstfewlines
 8        │           SparkJavaAjaxPostSample.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.SparkJavaAjaxPostSample'
 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    compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.3'
15}

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

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

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

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).

 1package com.firstfewlines;
 2import static spark.Spark.*;
 3
 4import org.apache.http.NameValuePair;
 5import org.apache.http.client.utils.URLEncodedUtils;
 6import java.nio.charset.Charset;
 7import java.util.HashMap;
 8import java.util.List;
 9import java.util.Map;
10
11public class SparkJavaAjaxPostSample {
12
13    public static void main(String [] argv){
14
15        staticFiles.location("/public");
16
17        post("/api/sum", (req, res) -> {
18
19            List<NameValuePair> pairs = URLEncodedUtils.parse(req.body(), Charset.defaultCharset());
20
21            Map<String, String> params = toMap(pairs);
22
23            try {
24                Integer a = Integer.parseInt(params.get("a"));
25                Integer b = Integer.parseInt(params.get("b"));
26                return a + b;
27            }
28            catch (Exception e){
29                return "Error: " + e.getMessage();
30            }
31        });
32    }
33
34    private static Map<String, String> toMap(List<NameValuePair> pairs){
35        Map<String, String> map = new HashMap<>();
36        for(int i=0; i<pairs.size(); i++){
37            NameValuePair pair = pairs.get(i);
38            map.put(pair.getName(), pair.getValue());
39        }
40        return map;
41    }
42}
43

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:
 1Starting a Gradle Daemon (subsequent builds will be faster)
 2:clean
 3:compileJava
 4:processResources
 5:classes
 6:run
 7[main] INFO spark.staticfiles.StaticFilesConfiguration - StaticResourceHandler configured with folder = /public
 8[Thread-0] INFO org.eclipse.jetty.util.log - Logging initialized @162ms to org.eclipse.jetty.util.log.Slf4jLog
 9[Thread-0] INFO spark.embeddedserver.jetty.EmbeddedJettyServer - == Spark has ignited ...
10[Thread-0] INFO spark.embeddedserver.jetty.EmbeddedJettyServer - >> Listening on 0.0.0.0:4567
11[Thread-0] INFO org.eclipse.jetty.server.Server - jetty-9.4.4.v20170414
12[Thread-0] INFO org.eclipse.jetty.server.session - DefaultSessionIdManager workerName=node0
13[Thread-0] INFO org.eclipse.jetty.server.session - No SessionScavenger set, using defaults
14[Thread-0] INFO org.eclipse.jetty.server.session - Scavenging every 600000ms
15[Thread-0] INFO org.eclipse.jetty.server.AbstractConnector - Started ServerConnector@6cbfdcfe{HTTP/1.1,[http/1.1]}{0.0.0.0:4567}
16[Thread-0] INFO org.eclipse.jetty.server.Server - Started @254ms
17

References:


Download the source code:


comments powered by Disqus