Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

after-action-before-render kind of interceptor (Play 1.x)

I know of the existence of @Before and @After, but @After happens to execute after the rendering of the template

Almost all my controllers extends a specific class of mine, and I want to, unobtrusively, be able to execute some code in my super class that checks for some conditions and sets some flash/renderArgs after the execution of the code in the subclass, but before the rendering is done

any simple way to achieve this?

edit: here's a snippet of the code

class MyController extends Controller {
   @After
   static void checkStage() {
      if (xyz) {
         flash.put("stage", "bla");
      }
   }
}

my controllers all extend MyController but since the checkStage code is called AFTER the rendering is done, the stage flash attribute will be rendered the next time a page is rendered

Actually, I would want to use flash.now instead of flash.put, but because the code @After code is executed after the rendering, it never shows up

like image 726
AndresQ Avatar asked Nov 03 '22 23:11

AndresQ


1 Answers

Well, if you want simplest: just insert the check code before you call render(). That is the most simple approach!

If you want something more complex, you could make a Plugin that overrides loadTemplate https://github.com/playframework/play/blob/master/framework/src/play/PlayPlugin.java#L157 and wraps the Template returned with your extra code. The other part of this you need to look at is the template loader: https://github.com/playframework/play/blob/master/framework/src/play/templates/TemplateLoader.java#L58 - Seems awfully convoluted, but could work.

Maybe you should explain why you are trying to do this pre-render code - there could be a better approach.


Edit: Ok, I see what you are trying to do. Yes, once the request is sent, you cannot modify cookies (aka flash). I'd suggest you avoid using cookies to maintain state between transactions - each variable adds to the HTTP transaction and is sent on every request.

Instead, I suggest you use Cache.set(Session.getId(), map) and put all the state values in the Map. Then I think you can save them during an @After

Example here; http://www.playframework.com/documentation/1.2.5/controllers#session

like image 114
Tom Carchrae Avatar answered Nov 11 '22 08:11

Tom Carchrae