How do I add headers to a response from spark, when using a transformer

11.3k Views Asked by At

I have this:

get ("/test", (req, resp) -> {
    return repository.getAll();
}, new JsonTransformer());

My transformer looks like:

public class JsonTransformer implements ResponseTransformer {

    ObjectMapper om = new ObjectMapper();

    public JsonTransformer() {
    }

    @Override
    public String render(Object o) throws Exception {
        return om.writeValueAsString(o);
    }
}

I've tried adding a header using the header funtion on response like so:

get ("/test", (req, resp) -> {
    resp.header("Content-Type", "application/json");
    return repository.getAll();
}, new JsonTransformer());

And I've tried this which I found in the docs: I think this sets the accept-type

get ("/test", "application/json", (req, resp) -> {
    return repository.getAll();
}, new JsonTransformer());

But nowhere I'm getting application/json as my Content-Type header

3

There are 3 best solutions below

0
On BEST ANSWER

You set the Content-Type of the response using the response.type function like so:

get("test", (req, resp) -> {
    resp.type("application/json");
    return repository.getAll() 
}, new JsonTransformer());
0
On

The third option is to use an after filter:

after((request, response) -> response.type("application/json"));

Please see: http://sparkjava.com/documentation#filters

2
On

Well after researching I found an elegant way to resolve this, I created an before method.

before((request, response) -> response.type("application/json"));

This would add the response type to json.

You can add it in after route but it may become troublesome later on. thx albertjan for your tip :)