close

  menu      DavidRodenas
CONTACT  

Sparkjava

Tags: java, rest

Sparkjava is a Sinatra inspired web framework for Java. It offers a minimal set of functionalities to build a web server.


Sparkjava is a micro framework inspired in

. It uses a functional approach to define a kind of DSL to build a minimal web interface. SparkJava is very useful to build

interfaces.

A quick view of the use of SparkJava is:

A web server will be running in port 4567. Try the URL http://localhost:4567/hello.

import static spark.Spark.*;
import spark.*;

public class HelloJSON {

   private static final ObjectMapper jacksonMapper= new ObjectMapper();
   public static void main(String[] args) {
   
      get(new Route("/hello") {
         @Override
         public Object handle(Request request, Response response) {
            return "Hello World!";
         }
      });
   }
}

With JSON

I use the library Jackson to retrieve and generate

results. In this library, by default, JSON objects are converted into Java Maps, and arrays into Java Lists. And vice-versa, Maps will be converted into JSON objects, and arrays, Lists and Sets, into JSON arrays. An example:

import static spark.Spark.*;
import spark.*;
import org.codehaus.jackson.map.ObjectMapper;
import java.util.Map;

public class HelloWorld {

   public static void main(String[] args) {
   
      get(new Route("/hello") {
         @Override
         public Object handle(Request request, Response response) {
           String result = null;
           try {
             Map value = jacksonMapper.readValue(request.body, Map.class);
			 String name = value.get("name");
			 value.put("salute","Hello "+name);
			 result = jacksonMapper.writeValueAsString(value);
           } catch (Throwable th) {
           }
           return result;
         }
      });
   }
}

Web server

By default SparkJava uses an embedded Jetty web server. But it can be configured to be used with Tomcat or any other web server application (it can be deployed as a .war container). See Running Spark on a Web Server for more details.