Search code examples
javajbosswicketwicket-6

Redirect all requests to a particular page in Wicket


I'm using Wicket 6.x and I want to implement the classic "site under maintenance" page, to which all requests should be redirected depending on a condition.

However, I don't want to write the redirect check on every page, since that would be redundant.

Is there a way I can intercept all requests, do my check, and execute the redirect if necessary, from a single place??


Solution

  • You can use IRequestCycleListener#onBeginRequest() + requestCycle.setResponsePage(MaintainancePage.class).

    Register your listener in MyApp#init(): getRequestCycleListeners().add(new MaintainanceListener()).

    Here is a possible solution:

    public class MaintainanceListener extends AbstractRequestCycleListener {
    
        @Override
        public void onRequestHandlerResolved(RequestCycle cycle, IRequestHandler handler) {
            super.onRequestHandlerResolved(cycle, handler);
            if (handler instanceof IPageRequestHandler && isMaintainanceMode()) {
                final Class<? extends IRequestablePage> pageClass = ((IPageRequestHandler) handler).getPageClass();
                if (MaintenancePage.class != pageClass) {
                    final MySession session = MySession.get();
                    if (session.getUser() != null) {
                        session.invalidateNow();
                    }
                    cycle.setResponsePage(MaintenancePage.class);
                }
            }
        }
    }