Friday, June 1, 2012

Wicket Request Cycle Customization

There are times where you'd need to add some custom logic in the Request Cycle itself. One example is when your site has single-sign-on integration with other sites. What that means is that you'd have to check the validity of the session from time to time.

Putting this checking logic in the Page class (or a general super-class Page) is not the answer, as you'd need to also perform these checks for Ajax requests that don't load a new page. The best way to do it is to add this logic into the Request Cycle.

In Wicket 1.5, the Request Cycle API as changed. To add some logic to the Request Cycle, create a concrete implementation of AbstractRequestCycleListener, and then add it from the Application object.

protected void init() {
    getRequestCycleListeners().add(new YourCustomizedRequestCycleListener());
}

In YourCustomizedRequestCycleListener, override 2 methods:
  • onRequestHandlerResolved:
    • The request cycle listener callbacks are called for all kinds of requests, including requests for CSS files and Images, by putting the session logic here, you'll be able to differentiate between Page / Ajax requests and other requests)
    • Page requests: Test handler to be of class RenderPageRequestHandler
    • Additionally, you may even need to check to exclude certain pages (e.g. public pages, error pages). Get the page class using this: ((RenderPageRequestHandler)handler).getPageProvider().getPageClass())
    • Ajax requests: Test handler to be of class ListenerInterfaceRequestHandler (which may also include non-Ajax requests but we want to include them too)
  • onException (if you need to send users to an error page, throw an exception inside onRequestHandlerResolved and handle it here)
    • To send user to error page: return new RenderPageRequestHandler(new PageProvider(ErrorPage.class));
Notes: This seems to be quite a lot of work to do something that's actually a pretty common requirement. Maybe there can be an easier way to do it. In any case, this works.

No comments:

Post a Comment