7 Basic HTTP
This chapter introduces how to deal with basic HTTP concerns such as parsing requests, rendering responses, content negotiation file uploads etc.
7.1 Request & Response
The context object that a handler operates on provides the (getRequest()
& getResponse()
methods for accessing the Request
and Response
respectively. These objects provide more or less what you would expect.
For example, they both provide a getHeaders()
method that returns an model of the HTTP headers sent with the request and a model of the HTTP headers that are to be sent with the response. The Request
exposes other metadata attributes such as the HTTP method, the URI and a key/value model of the query string parameters among other things.
7.2 Reading the request
TODO introduce parsers generally
7.2.1 Forms
Ratpack provides a parser for Form
objects in the core. This can be used for reading POST’d (or PUT’d etc. for that matter) forms, both URL encoded and multi part (including file uploads).
Here’s an example of using this from Java…
import ratpack.handling.Handler;
import ratpack.handling.Context;
import ratpack.form.Form;
import ratpack.form.UploadedFile;
public class MyHandler implements Handler {
public void handle(Context context) {
Form form = context.parse(Form.class);
// Get the first attribute sent with name “foo”
String foo = form.get("foo");
// Get all attributes sent with name “bar”
List<String> bar = form.getAll("bar");
// Get the file uploaded with name “myFile”
UploadedFile myFile = form.file("myFile");
// Send back a response …
}
}
See Form
and UploadedFile
for more information and examples.
7.3 Sending a response
TODO introduce status methods
TODO introduce send methods
TODO introduce renderers
TODO introduce sendFile methods (pointing to use of render(file(«path»)))
instead.
Cookies
TODO introduce getCookies() on request and response
TODO introduce Request#oneCookie()
TODO introduce Response#expireCookie()
7.5 Sessions
TODO introduce ratpack-sessions library