<commit_before>---
layout: default
title: Docs
rightmenu: true
permalink: /documentation/
---

<div class="right-menu" markdown="1">
* [Getting Started](#getting-started)
* [Stopping the Server](#stopping-the-server)
* [Routes](#routes)
* [Request](#request)
* [Response](#response)
* [Query Maps](#query-maps)
* [Cookies](#cookies)
* [Sessions](#sessions)
* [Halting](#halting)
* [Filters](#filters)
* [Redirects](#redirects)
* [Error Handling](#error-handling)
* [Exception Mapping](#exception-mapping)
* [Static Files](#static-files)
* [ResponseTransformer](#response-transformer)
* [Views and Templates](#views-and-templates)
* [Embedded Webserver](#embedded-web-server)
  * [- Port](#port)
  * [- Secure](#secure)
  * [- ThreadPool](#threadpool)
  * [- Await initialization](#awaitinit)
  * [- WebSockets](#websockets)
* [Other Webserver](#other-web-server)
* [GZIP](#gzip)
* [Javadoc](#javadoc)
* [Examples/FAQ](#examples-and-faq)
</div>

<h1 id="getting-started" class="no-margin-top">Getting started</h1>

**1:** Create a new maven project and add the dependency to your [POM.xml](http://maven.apache.org/pom.html):
{% include macros/mavenDep.md %}

**2:** Start coding:
~~~java
import static spark.Spark.*;

public class HelloWorld {
    public static void main(String[] args) {
        get("/hello", (req, res) -> "Hello World");
    }
}
~~~

**3:** Run and view:
~~~bash
http://localhost:4567/hello
~~~

To see more console output from Spark (debug info, etc), you have to [add a logger](#add-a-logger) to your project.

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

~~~java
stop();
~~~

## What about starting the server?
The server is automatically started when you do something that requires the server to be started (i.e. declaring a route or setting the port). You can also manually start the server by calling `init()`.

# 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.  
Always statically import Spark methods to ensure good readability:

~~~java
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 can include named parameters, accessible via the `params()` method on the request object:
~~~java
// 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 can also include splat (or wildcard) parameters. These parameters can be accessed by using the `splat()` method on the request object:

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

## Path groups
If you have a lot of routes, it can be helpful to separate them into groups. This can be done by calling the `path()` method, which takes a `String prefix` and gives you a scope to declare routes and filters (or nested paths) in:

~~~java
path("/api", () -> {
    before("/*", (q, a) -> log.info("Received api call"));
    path("/email", () -> {
        post("/add",       EmailApi.addEmail);
        put("/change",     EmailApi.changeEmail);
        delete("/remove",  EmailApi.deleteEmail);
    });
    path("/username", () -> {
        post("/add",       UserApi.addUsername);
        put("/change",     UserApi.changeUsername);
        delete("/remove",  UserApi.deleteUsername);
    });
});
~~~

# Request
Request information and functionality is provided by the request parameter:
~~~java
request.attributes();             // the attributes list
request.attribute("foo");         // value of foo attribute
request.attribute("A", "V");      // sets value of attribute A to V
request.body();                   // request body sent by the client
request.bodyAsBytes();            // request body as bytes
request.contentLength();          // length of request body
request.contentType();            // content type of request.body
request.contextPath();            // the context path, e.g. "/hello"
request.cookies();                // request cookies sent by the client
request.headers();                // the HTTP header list
request.headers("BAR");           // value of BAR header
request.host();                   // the host, e.g. "example.com"
request.ip();                     // client IP address
request.params("foo");            // value of foo path parameter
request.params();                 // map with all parameters
request.pathInfo();               // the path info
request.port();                   // the server port
request.protocol();               // the protocol, e.g. HTTP/1.1
request.queryMap();               // the query map
request.queryMap("foo");          // query map for a certain parameter
request.queryParams();            // the query param list
request.queryParams("FOO");       // value of FOO query param
request.queryParamsValues("FOO")  // all values of FOO query param
request.raw();                    // raw request handed in by Jetty
request.requestMethod();          // The HTTP method (GET, ..etc)
request.scheme();                 // "http"
request.servletPath();            // the servlet path, e.g. /result.jsp
request.session();                // session management
request.splat();                  // splat (*) parameters
request.uri();                    // the uri, e.g. "http://example.com/foo"
request.url();                    // the url. e.g. "http://example.com/foo"
request.userAgent();              // user agent
~~~

# Response
Response information and functionality is provided by the response parameter:

~~~java
response.body();               // get response content
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();             // get the response status
response.status(401);          // set status code to 401
response.type();               // get the content type
response.type("text/xml");     // set content type to 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.
~~~java
request.queryMap().get("user", "name").value();
request.queryMap().get("user").get("name").value();
request.queryMap("user").get("age").integerValue();
request.queryMap("user").toMap();
~~~

# Cookies
~~~java
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
~~~

# Sessions
Every request has access to the session created on the server side, provided with the following methods:
~~~java
request.session(true)                      // create and return session
request.session().attribute("user")        // Get session attribute 'user'
request.session().attribute("user", "foo") // Set session attribute 'user'
request.session().removeAttribute("user")  // Remove session attribute 'user'
request.session().attributes()             // Get all session attributes
request.session().id()                     // Get session id
request.session().isNew()                  // Check if session is new
request.session().raw()                    // Return servlet object
~~~

# Halting
To immediately stop a request within a filter or route use `halt()`:
~~~java
halt();                // halt 
halt(401);             // halt with status
halt("Body Message");  // halt with message
halt(401, "Go away!"); // halt with status and message
~~~

# Filters
Before-filters are evaluated **before each request**, and can read the request and read/modify the response.  
To stop execution, use `halt()`:<commit_msg>[docs] Add initExceptionHandler() info, clarify halt() usage<commit_after>---
layout: default
title: Docs
rightmenu: true
permalink: /documentation/
---

<div class="right-menu" markdown="1">
* [Getting Started](#getting-started)
* [Stopping the Server](#stopping-the-server)
* [Routes](#routes)
* [Request](#request)
* [Response](#response)
* [Query Maps](#query-maps)
* [Cookies](#cookies)
* [Sessions](#sessions)
* [Halting](#halting)
* [Filters](#filters)
* [Redirects](#redirects)
* [Error Handling](#error-handling)
* [Exception Mapping](#exception-mapping)
* [Static Files](#static-files)
* [ResponseTransformer](#response-transformer)
* [Views and Templates](#views-and-templates)
* [Embedded Webserver](#embedded-web-server)
  * [- Port](#port)
  * [- Secure](#secure)
  * [- ThreadPool](#threadpool)
  * [- Await initialization](#awaitinit)
  * [- WebSockets](#websockets)
* [Other Webserver](#other-web-server)
* [GZIP](#gzip)
* [Javadoc](#javadoc)
* [Examples/FAQ](#examples-and-faq)
</div>

<h1 id="getting-started" class="no-margin-top">Getting started</h1>

**1:** Create a new maven project and add the dependency to your [POM.xml](http://maven.apache.org/pom.html):
{% include macros/mavenDep.md %}

**2:** Start coding:
~~~java
import static spark.Spark.*;

public class HelloWorld {
    public static void main(String[] args) {
        get("/hello", (req, res) -> "Hello World");
    }
}
~~~

**3:** Run and view:
~~~bash
http://localhost:4567/hello
~~~

To see more console output from Spark (debug info, etc), you have to [add a logger](#add-a-logger) to your project.

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

~~~java
stop();
~~~

## Wait, what about starting the server?
The server is automatically started when you do something that requires the server to be started (i.e. declaring a route or setting the port). You can also manually start the server by calling `init()`.

You can specify what should happen if initialization fails: 

~~~java
initExceptionHandler((e) -> System.out.println("Uh-oh"));
~~~

The default behaviour is to log and shut down: 
~~~java
private Consumer<Exception> initExceptionHandler = (e) -> {
    LOG.error("ignite failed", e);
    System.exit(100);
};
~~~

# 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.  
Always statically import Spark methods to ensure good readability:

~~~java
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 can include named parameters, accessible via the `params()` method on the request object:
~~~java
// 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 can also include splat (or wildcard) parameters. These parameters can be accessed by using the `splat()` method on the request object:

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

## Path groups
If you have a lot of routes, it can be helpful to separate them into groups. This can be done by calling the `path()` method, which takes a `String prefix` and gives you a scope to declare routes and filters (or nested paths) in:

~~~java
path("/api", () -> {
    before("/*", (q, a) -> log.info("Received api call"));
    path("/email", () -> {
        post("/add",       EmailApi.addEmail);
        put("/change",     EmailApi.changeEmail);
        delete("/remove",  EmailApi.deleteEmail);
    });
    path("/username", () -> {
        post("/add",       UserApi.addUsername);
        put("/change",     UserApi.changeUsername);
        delete("/remove",  UserApi.deleteUsername);
    });
});
~~~

# Request
Request information and functionality is provided by the request parameter:
~~~java
request.attributes();             // the attributes list
request.attribute("foo");         // value of foo attribute
request.attribute("A", "V");      // sets value of attribute A to V
request.body();                   // request body sent by the client
request.bodyAsBytes();            // request body as bytes
request.contentLength();          // length of request body
request.contentType();            // content type of request.body
request.contextPath();            // the context path, e.g. "/hello"
request.cookies();                // request cookies sent by the client
request.headers();                // the HTTP header list
request.headers("BAR");           // value of BAR header
request.host();                   // the host, e.g. "example.com"
request.ip();                     // client IP address
request.params("foo");            // value of foo path parameter
request.params();                 // map with all parameters
request.pathInfo();               // the path info
request.port();                   // the server port
request.protocol();               // the protocol, e.g. HTTP/1.1
request.queryMap();               // the query map
request.queryMap("foo");          // query map for a certain parameter
request.queryParams();            // the query param list
request.queryParams("FOO");       // value of FOO query param
request.queryParamsValues("FOO")  // all values of FOO query param
request.raw();                    // raw request handed in by Jetty
request.requestMethod();          // The HTTP method (GET, ..etc)
request.scheme();                 // "http"
request.servletPath();            // the servlet path, e.g. /result.jsp
request.session();                // session management
request.splat();                  // splat (*) parameters
request.uri();                    // the uri, e.g. "http://example.com/foo"
request.url();                    // the url. e.g. "http://example.com/foo"
request.userAgent();              // user agent
~~~

# Response
Response information and functionality is provided by the response parameter:

~~~java
response.body();               // get response content
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();             // get the response status
response.status(401);          // set status code to 401
response.type();               // get the content type
response.type("text/xml");     // set content type to 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.
~~~java
request.queryMap().get("user", "name").value();
request.queryMap().get("user").get("name").value();
request.queryMap("user").get("age").integerValue();
request.queryMap("user").toMap();
~~~

# Cookies
~~~java
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
~~~

# Sessions
Every request has access to the session created on the server side, provided with the following methods:
~~~java
request.session(true)                      // create and return session
request.session().attribute("user")        // Get session attribute 'user'
request.session().attribute("user", "foo") // Set session attribute 'user'
request.session().removeAttribute("user")  // Remove session attribute 'user'
request.session().attributes()             // Get all session attributes
request.session().id()                     // Get session id
request.session().isNew()                  // Check if session is new
request.session().raw()                    // Return servlet object
~~~

# Halting
To immediately stop a request within a filter or route use `halt()`:
~~~java
halt();                // halt 
halt(401);             // halt with status
halt("Body Message");  // halt with message
halt(401, "Go away!"); // halt with status and message
~~~

`halt()` is not intended to be used inside exception-mappers.

# Filters
Before-filters are evaluated **before each request**, and can read the request and read/modify the response.  
To stop execution, use `halt()`:
{'fraction_non_alphanumeric': 0.15308628195111063, 'fraction_numerical': 0.003962495814264985, 'mean_word_length': 2.906474820143885, 'pattern_counts': {'":': 4, '<': 12, '<?xml version=': 0, '>': 40, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 6}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7078163', 'n_tokens_mistral': 5033, 'n_tokens_neox': 4770, 'n_words': 1721}