Phoenix makes it easy to render HTML pages or JSON response from a controller. Normally, you will
need to use Spring's ResponseEntity
, however Phoenix simplifies this by offering a
single tech.petrepopescu.phoenix.format.Result
that can be either an HTML page or a
JSON result. Furthermore, Phoenix makes it easy to send any HTTP status code using
tech.petrepopescu.phoenix.format.PhoenixResponse
. There are predefined methods
PhoenixResponse.ok()
and PhoenixResponse.notFound()
, or just use
PhoenixResponse.withHttpStatus()
to send any HTTP status code.
The mentioned methods accept any Java object and it will provide a JSON response to the user. The
power of Phoenix, however, lies in it's ability to render HTML pages. If the PhoenixResponse
receives a Phoenix View as an input, it will be rendered as an HTML page. This can be done by
calling View.of()
with the template name and input parameters.
Input parameters must be provided in the same order and have the same type as the ones declared
in the template's argument (@args()
) block. Since Phoenix supports importing any
class from your code, you can provide complex objects as input parameters and send them directly
from the controller.
import tech.petrepopescu.phoenix.format.Result;
import tech.petrepopescu.phoenix.views.View;
import static tech.petrepopescu.phoenix.format.PhoenixResponse.ok;
@Controller
public class TestController {
@GetMapping("/test.html")
public Result renderTest(@RequestParam(name = "a", defaultValue = "0") int a,
@RequestParam(name = "b", defaultValue = "0") int b) {
return ok(View.of("test", a, b));
}
@GetMapping("/json")
public Result renderJson() {
return ok(Arrays.asList("Test", "test2"));
}
}
The view name is relative to the views
directory, with .
being used as
path separator. templates that are directly in the views
directory will be
refferenced by the name, while those that are in sub-directories will have the directory path
pre-pendend.
Example: View.of("myView")
Example: View.of("subFolder.myScondView")