Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Portable REST using Spark Framework

DZone's Guide to

Portable REST using Spark Framework

· Java Zone ·
Free Resource

Java-based (JDBC) data connectivity to SaaS, NoSQL, and Big Data. Download Now.

Today, i will write some tiny-tutorial how to create a portable REST using Spark MVC Framework, http://sparkjava.com/. Spark is very lite and would be a good choice -and an alternative of SpringMVC- if you are developing a small project of MVC/REST.

  1. Create your Maven project and add this dependency. Notes here, i’m using Java 6 for my development and i’m too lazy to point to Java 8, so i’m using the version 0.9.9.3-SNAPSHOT of Spark. You are welcomed to use the newest version of Spark. Please refer to http://sparkjava.com/download.html.

    <dependency>
    <groupId>spark</groupId>
    <artifactId>spark</artifactId>
    <version>0.9.9.3-SNAPSHOT</version>
    </dependency>

    And this to your repository

    <repository>
    <id>Spark repository</id>
    <url>http://www.sparkjava.com/nexus/content/repositories/spark/</url>
    </repository>
  2. Code your application here.

    Dont forget to put the code inside of your main function, so it could be called from the command prompt.

    package com.namex.spark;
     
    import spark.Request;
    import spark.Response;
    import spark.Route;
    import spark.Spark;
     
    public class SparkHelloWorld {
        public static void main(String[] args) {
            Spark.get(new Route("/SparkHelloWorld/:name") {
     
                @Override
                public Object handle(Request req, Response res) {
                    // to get the parameter
                    String nameFromParam = req.params(":name");
                    String jsonString = "{\"message\": \"Spark Hello World\", \"name\": \"" + nameFromParam + "\"}";
                    return jsonString;
                }
            });
        }
    }
  3. Run the SparkHelloWorld class, and open this url from your web browserhttp://localhost:4567/SparkHelloWorld/namingexception.

JbNIxZN

Connect any Java based application to your SaaS data.  Over 100+ Java-based data source connectors.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}