Home > Java > Portable REST using Spark Framework

Portable REST using Spark Framework

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 of Spark. You are welcomed to use the newest version of Spark. Please refer to http://sparkjava.com/download.html.

    And this to your repository

    	<id>Spark repository</id>
  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") {
    			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 browser http://localhost:4567/SparkHelloWorld/namingexception.



That’s all. It’s so simple and easy. Even though i have to admit Spark might not suitable for big-scale project, still it’s a good option to be considered.

Categories: Java Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: