Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 694
albertjan Avatar asked Nov 12 '14 19:11

albertjan


People also ask

Does spark use Jetty?

Spark is a compact framework for building web applications that run on the JVM. It comes with an embedded web server, Jetty, so you can get started in minutes.

What is a spark route?

In the Spark lingo, a route is a handler A route is a URL pattern that is mapped to a handler. A handler can be a physical file or a $ gradle run. We run the application with gradle run command. An embedded Jetty server is started. $ curl localhost:4567/hello Hello there!

How do I stop Java spark Server?

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


2 Answers

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());
like image 159
albertjan Avatar answered Oct 20 '22 12:10

albertjan


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

like image 31
Gabriel Avatar answered Oct 20 '22 13:10

Gabriel