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

From the Spark Java documentation :

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

And from the JavaDoc Route :

 @return The content to be set in the response 

And what's the difference? Can someone explain me pls?

+5
source share
3 answers

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

response.body() should mainly be used in exception handlers and after filters and the return callback on regular routes.

+6
source

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

response.body () is useful for handling exceptions.

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

Sparkjava is the bare base of the bones and it must be built on top. response.body () makes sparkjava easily extensible in contexts where you do not have access to the return object.

+1
source

In fact, there is no difference in what he does, but they both exist, so it’s easy to set the body of the response in different contexts. For example, you can use response.body in an exception handler or even in a filter, but as you can see, the return method is "better" in the route declaration.

+1
source

Source: https://habr.com/ru/post/1242494/


All Articles