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

3

10

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

Mantis answered 12/11, 2014 at 19:35 Comment(3)
i would consider changing your spark tag. That seems to be for the apache spark computation framework, not the ws framework.Microanalysis
How did you solve it? I added "response.type("application/json");" It works but is there any nicer way?Discordant
@Discordant no thats it. Thats what I did too.Mantis
M
6

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());
Mantis answered 12/11, 2014 at 20:5 Comment(0)
D
17

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 :)

Discordant answered 6/1, 2015 at 10:1 Comment(2)
If json is your primary response-type the before route is a good solution. The after route could become troublesome later on.Mantis
Thanks for your reply, I did try both but i ended up using before as it was cleaner and i still have the opportunity to change the response.type in the route itself if needed.Discordant
M
6

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());
Mantis answered 12/11, 2014 at 20:5 Comment(0)
J
2

The third option is to use an after filter:

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

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

Johst answered 5/9, 2017 at 14:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.