In a recent write-up, I described how to create a custom route in Javalin - one which allows me to override standard requests. That approach works, but makes use of Javalin’s error handling mechanism for something which is not actually an error.

My thanks to Tipsy (the creator of Javalin) for making me aware of an alternative approach which does not rely on Javalin’s error handling.

Note: It does require Javalin version 5 - so this won’t work for v4.

In Javalin 5, you can cast this…

io.javalin.http.Context

…to this:

io.javalin.http.servlet.JavalinServletContext

This, in turn, gives you access to some additional methods - including getTasks(), which is a Java double-ended queue - a deque (pronounced “deck”), consisting of io.javalin.http.servlet.Task objects. I don’t know much at all about what is happening under the covers, here. I assume the deque includes the “before” handler (if you have one) and the submitted request.

My new approach using this new object is to remove all tasks from the deque and then submit the task I want to execute, instead:

1
2
3
4
5
6
// clear the deque:
JavalinServletContext jsc = (JavalinServletContext) ctx;
jsc.getTasks().clear();
// submit my replacement task:
model.put(...);
ctx.render("my_special_resonse_page.html", model);

That’s it. Much cleaner than the previous approach.