What's the difference between response.body() and object returned by the callback?
Asked Answered
C

3

9

From Spark Java documentation:

response.body("Hello");        // sets content to Hello

And from Route's JavaDoc:

@return The content to be set in the response

So what's the difference? Could someone explain to me pls?

Cyte answered 7/2, 2016 at 17:33 Comment(0)
C
8

An actual difference however is that response.body() accepts only String, while in the callback you can return any object that can be serialized to String and most importantly streams.

response.body() should be mostly used in exception handlers and after filters, and the callback return in normal routes.

Cheltenham answered 15/2, 2016 at 16:39 Comment(0)
P
1

As you've pointed out, they both can be used to set the response body. I think the @return is part of a typical http endpoint.

response.body() is useful for exception handling.

exception(NotFoundException.class, (e, request, response) -> {
    response.status(404);
    response.body("Resource not found");
});

Sparkjava is a bare bones framework and it's meant to be built on top of. response.body() makes sparkjava easily extensible in contexts where you don't have access to the "return" object.

Peart answered 9/2, 2016 at 5:18 Comment(0)
M
1

There's really no difference on what it does, but they both exist so it's easy to set the response body in different contexts. For example you could use response.body in an exception handler or even filter, but as you may notice, the return way is "nicer" in a route declaration.

Monochasium answered 10/2, 2016 at 20:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.