Fork me on GitHub
A Sinatra inspired micro web framework for quickly creating web applications in Java with minimal effort

Getting started

Add the Spark maven dependency
Start coding:
import static spark.Spark.*;

public class HelloWorld {

   public static void main(String[] args) {
      get("/hello",(request, response) -> {
         return "Hello World!";


Ignite and view at:


The main building block of a Spark application is a set of routes. A route is made up of three simple pieces:
  • A verb (get, post, put, delete, head, trace, connect, options)
  • A path (/hello, /users/:name)
  • A callback (request, response) -> { }

NOTE! Routes are matched in the order they are defined. The first route that matches the request is invoked.

 get("/", (request, response) -> {
    // .. Show something ..
 post("/", (request, response) -> {
    // .. Create something .. 
 put("/", (request, response) -> {
    // .. Update something ..
 delete("/", (request, response) -> {
    // .. annihilate something ..
 options("/", (request, response) -> {
    // .. appease something ..

Route patterns may include named parameters, accessible via the params method on the request object:

 // matches "GET /hello/foo" and "GET /hello/bar"
 // request.params(":name") is 'foo' or 'bar'
 get("/hello/:name", (request, response) -> {
    return "Hello: " + request.params(":name");

Route patterns may also include splat (or wildcard) parameters, accessible via the splat method on the request object:

 // matches "GET /say/hello/to/world"
 // request.splat()[0] is 'hello' and request.splat()[1] 'world'
 get("/say/*/to/*", (request, response) -> {
       return "Nbr of splat parameters: " + request.splat().length;


In the handle method request information and functionality is provided by the request parameter:

 request.body();               // request body sent by the client
 request.cookies();            // request cookies sent by the client
 request.contentLength();      // length of request body
 request.contentType();        // content type of request.body
 request.headers();            // the HTTP header list
 request.headers("BAR");       // value of BAR header
 request.attributes();         // the attributes list
 request.attribute("foo");     // value of foo attribute
 request.attribute("A", "V");  // sets value of attribute A to V;               // ""
 request.ip();                 // client IP address
 request.pathInfo();           // the path info
 request.params("foo");        // value of foo path parameter
 request.params();             // map with all parameters
 request.port();               // the server port
 request.queryMap();           // the query map
 request.queryMap("foo");      // query map for a certain parameter
 request.queryParams("FOO");   // value of FOO query param
 request.queryParams();        // the query param list
 request.raw();                // raw request handed in by Jetty
 request.requestMethod();      // The HTTP method (GET, ..etc)
 request.scheme();             // "http"
 request.session();            // session management
 request.splat();              // splat (*) parameters
 request.url();                // ""
 request.userAgent();          // user agent

Query maps

Query maps allows you to group parameters to a map by their prefix. This allows you to group two parameters like user[name] and user[age] to a user map.

request.queryMap().get("user", "name").value();


In the handle method response information and functionality is provided by the response parameter:

 response.body("Hello");        // sets content to Hello
 response.header("FOO", "bar"); // sets header FOO with value bar
 response.raw();                // raw response handed in by Jetty
 response.redirect("/example"); // browser redirect to /example
 response.status(401);          // set status code to 401
 response.type("text/xml");     // set content type to text/xml

Stopping the server

By calling the stop() method the server is stopped and all routes are cleared.


Handling cookies can be done via spark request and response objects.

 request.cookies();     // get map of all request cookies 
 request.cookie("foo"); // access request cookie by name
 response.cookie("foo", "bar");       // set cookie with a value
 response.cookie("foo", "bar", 3600); // set cookie with a max-age
 response.cookie("foo", "bar", 3600, true); // secure cookie
 response.removeCookie("foo");        // remove cookie

Session management

Every request has access to the session created on the server side, provided with the following methods:

 request.session(true)                            // create (if not created) and return session
 request.session().attribute("user")              // Get session attribute 'user'
 request.session().attribute("user", "foo")       // Set session attribute 'user'
 request.session().removeAttribute("user", "foo") // Remove session attribute 'user'
 request.session().attributes()                   // Get all session attributes
 request.session().id()                           // Get session id
 request.session().isNew()                        // Check is session is new
 request.session().raw()                          // Return servlet object


To immediately stop a request within a filter or route use:


You can also specify the status when halting:


Or the body:

 halt("This is the body");

Or both:

 halt(401, "Go Away!");


Before filters are evaluated before each request and can read the request and read/modify the response. To stop execution, use halt:

 before((request, response) -> {
    boolean authenticated;
    // ... check if authenticated
    if (!authenticated) {
       halt(401, "You are not welcome here");

After filters are evaluated after each request and can read the request and read/modify the response:

 after((request, response) -> {
    response.header("foo", "set by after filter");

Filters optionally take a pattern, causing them to be evaluated only if the request path matches that pattern:

 before("/protected/*", (request, response) -> {
    // ... check if authenticated
    halt(401, "Go Away!");

Browser Redirect

You can trigger a browser redirect with the redirect helper method:


You can also trigger a browser redirect with specific http 3XX status code:

 response.redirect("/bar", 301); // moved permanently

Exception Mapping

To handle exceptions of a configured type for all routes and filters:

 get("/throwexception", (request, response) -> {
    throw new NotFoundException();

 exception(NotFoundException.class, (e, request, response) -> {
    response.body("Resource not found");

Static files

Assign a folder in the classpath serving static files with the staticFileLocation method.

 staticFileLocation("/public"); // Static files 
Note that the public directory name is not included in the URL. A file /public/css/style.css is made available as http://<host>:<port>/css/style.css

You can also assign an external folder (not in the classpath) serving static files with the externalStaticFileLocation method.

 externalStaticFileLocation("/var/www/public"); // Static files 


Mapped routes that transforms the output from the handle method. This is done by extending the ResponseTransformer and pass this to the mapping method.
Example Of a route transforming output to JSON using Gson:


 public class JsonTransformer implements ResponseTransformer {

    private Gson gson = new Gson();
    public String render(Object model) {
       return gson.toJson(model);

and how it is used (MyMessage is a bean with one member 'message'):

 get("/hello", "application/json", (request, response) -> {
     return new MyMessage("Hello World");
 }, new JsonTransformer());

Views / Templates - TemplateEngine

A TemplateViewRoute is built up by a path (for url-matching) and the template engine holding the implementation of the 'render' method. Instead of returning the result of calling toString() as body the TemplateViewRoute returns the result of calling render method.

The primary purpose of this kind of Route is to provide a way to create generic and reusable components for rendering output using a Template Engine.

NEWS: The available implementations HAVE been updated to support Spark 2.0.0 Available TemplateEngine implementations:

-- FreeMarker

Renders objects to HTML using Freemarker template engine.

Maven dependency:

-- Apache Velocity

Renders objects to HTML using the Apache Velocity template engine.

Maven dependency:

-- Mustache

Renders objects to HTML using the Mustache template engine.

Maven dependency:


By default, Spark runs on port 4567. If you want to set another port use setPort. This has to be done before using routes and filters:

 setPort(9090); // Spark will run on port 9090

Embedded Web Server

Standalone Spark runs on an embedded Jetty web server.

Running Spark on a Web Server, e.g. Tomcat

To run Spark on a web server instead of standalone first of all an implementation of the interface spark.servlet.SparkApplication is needed. In the init() method the routes should be initialized. In your web.xml the following filter needs to be configured:



Javadoc is available in the zip files that can be downloaded from the project's page at google code


Examples can be found on the project's page at google code