Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

spark-java

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?

like image 509
FuzzY Avatar asked Feb 07 '16 17:02

FuzzY


2 Answers

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.

like image 89
k.liakos Avatar answered Oct 20 '22 12:10

k.liakos


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.

like image 42
thebiggestlebowski Avatar answered Oct 20 '22 13:10

thebiggestlebowski