Wednesday, 14 January 2015

Spark Java


Spark java is a micro frame work, used to build web applications with minimal effort. It is a pure java alternative for developers, who want to develop web applications. Without discussing much theory let’s start building web applications using spark.

Step 1: Add Maven dependency
<dependency>
 <groupId>com.sparkjava</groupId>
 <artifactId>spark-core</artifactId>
 <version>2.1</version>
</dependency>


Note:  If you don’t want to work with Maven, you can download spark jar files and place them in classpth.

Step 2: Write simple Application, which displays welcome page.
import static spark.Spark.*;
import spark.Request;
import spark.Response;
import spark.Route;

public class HelloSpark {
 public static void main(String[] args) { 
  get("/welcome", new Route(){
   @Override
   public Object handle(Request request, Response response)  throws Exception{
    return "Welcome to Spark Development";
   }
  });
  
 }

}


Run “HelloSpark.java” and view.




If you are using Java 8 or more, then you can use Lambda expressions like below.

get("/welcome", (req, res) -> "Welcome to Spark Development");


import static spark.Spark.*;

public class HelloSpark {
	public static void main(String[] args) {	
		get("/welcome", (req, res) -> "Welcome to Spark Development");
	}

}


get("/welcome", (req, res) -> "Welcome to Spark Development");
Observe above statement, It is divided into three portions.
1.   Verb (get) : it is type of request. Spark supports all HTTP requests like get, post, put, delete, head, trace, connect, options.
2.   Path (“/welcome”) :
3.   Callback : (request, response) -> { }

In subsequent posts, we will see some basic features of spark framework.


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment