Getting started
Add the maven dependency:
<dependency>
<groupId>com.sparkjava</groupId>
<artifactId>spark-core</artifactId>
<version>2.0.0</version>
</dependency>
Start coding:
import static spark.Spark.*;
public class HelloWorld {
public static void main(String[] args) {
get("/hello", (req, res) -> "Hello World");
}
}
Run and view:
http://localhost:4567/hello
That was easy, right? Spark is the simplest Java web framework to set up, while still providing enough functionality for many types of projects.
Stopping the Server
By calling the stop() method the server is stopped and all routes are cleared.
Routes
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) -> { }
Routes are matched in the order they are defined. The first route that matches the request is invoked.
get("/", (request, response) -> {
});
post("/", (request, response) -> {
});
put("/", (request, response) -> {
});
delete("/", (request, response) -> {
});
options("/", (request, response) -> {
});
Route patterns can include named parameters, accessible via the params method on the request object:
get("/hello/:name", (request, response) -> {
return "Hello: " + request.params(":name");
});
Route patterns can also include splat (or wildcard) parameters. These parameters can be accessed by using the splat method on the request object:
get("/say/*/to/*", (request, response) -> {
return "Number of splat parameters: " + request.splat().length;
});
Request
In the handle method request information and functionality is provided by the request parameter:
request.body(); request.cookies(); request.contentLength(); request.contentType(); request.headers(); request.headers("BAR"); request.attributes(); request.attribute("foo"); request.attribute("A", "V"); request.host(); request.ip(); request.pathInfo(); request.params("foo"); request.params(); request.port(); request.queryMap(); request.queryMap("foo"); request.queryParams("FOO"); request.queryParams(); request.raw(); request.requestMethod(); request.scheme(); request.session(); request.splat(); request.url(); request.userAgent();
Response
In the handle method response information and functionality is provided by the response parameter:
response.body("Hello"); response.header("FOO", "bar"); response.raw(); response.redirect("/example"); response.status(401); response.type("text/xml");
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();
request.queryMap().get("user").get("name").value();
request.queryMap("user").get("age").integerValue();
request.queryMap("user").toMap();
Cookies
request.cookies(); request.cookie("foo"); response.cookie("foo", "bar"); response.cookie("foo", "bar", 3600); response.cookie("foo", "bar", 3600, true); response.removeCookie("foo");
Sessions
Every request has access to the session created on the server side, provided with the following methods:
request.session(true) request.session().attribute("user") request.session().attribute("user", "foo") request.session().removeAttribute("user", "foo") request.session().attributes() request.session().id() request.session().isNew() request.session().raw()
Halting
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:
Filters
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;
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) -> {
halt(401, "Go Away!");
});
Redirects
You can trigger a browser redirect with the redirect helper method:
response.redirect("/bar");
You can also trigger a browser redirect with specific http 3XX status code:
response.redirect("/bar", 301);
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.status(404);
response.body("Resource not found");
});
Static Files
You can assign a folder in the classpath serving static files with the staticFileLocation method. 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
staticFileLocation("/public");
You can also assign an external folder (not in the classpath) serving static files with the externalStaticFileLocation method.
externalStaticFileLocation("/var/www/public");
ResponseTransformer
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:
import com.google.gson.Gson;
public class JsonTransformer implements ResponseTransformer {
private Gson gson = new Gson();
@Override
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 and Templates
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.
Freemarker
Renders objects to HTML using the Freemarker template engine.
Maven dependency:
<dependency>
<groupId>com.sparkjava</groupId>
<artifactId>spark-template-freemarker</artifactId>
<version>2.0.0</version>
</dependency>
Velocity
Renders objects to HTML using the Velocity template engine.
Maven dependency:
<dependency>
<groupId>com.sparkjava</groupId>
<artifactId>spark-template-velocity</artifactId>
<version>2.0.0</version>
</dependency>
Mustache
Renders objects to HTML using the Mustache template engine.
Maven dependency:
<dependency>
<groupId>com.sparkjava</groupId>
<artifactId>spark-template-mustache</artifactId>
<version>1.0.0</version>
</dependency>
Port
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:
Embedded webserver
Standalone Spark runs on an embedded Jetty web server.
Other webserver
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:
<filter>
<filter-name>SparkFilter</filter-name>
<filter-class>spark.servlet.SparkFilter</filter-class>
<init-param>
<param-name>applicationClass</param-name>
<param-value>com.company.YourApplication</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SparkFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Javadoc
After getting the source from GitHub run:
The result is put in /target/site/apidocs
Examples
Examples can be found on the project's page on GitHub
Spark is created and maintained by
Per Wendel. Logo and website by
David Åse