Andreas Krueger Andreas Krueger - 1 month ago 13
Java Question

How to automatically redirect from one page to another within a few seconds

The idea is to display a

PageExpiredPage
that is visible for a few seconds and automatically redirects to the
HomePage
, when the web session expires.

By the following code the
PageExpiredPage
displays with a bookmarkable link to the
HomePage
on it.


PageExpiredPage.html:


Your session expired, log in anew by clicking
<a wicket:id="lnk-home-page" href="#"> here</a>
...



PageExpiredPage.java:


final Application app = Session.get().getApplication();
BookmarkablePageLink<? extends Page> lnkHomePage = new BookmarkablePageLink<? extends Page>("lnk-home-page", app.getHomePage());
add(lnkHomePage);
...


How to code in Wicket that the
PageExpiredPage
, when displayed, automatically redirects to
HomePage
after a configurable number of seconds?

Answer

A better solution than the RedirectPage is a custom behaviour. The obvious problem with RedirectPage is that you can't use a common base class for the layout of the page.

public class RedirectBehavior extends Behavior {

    private final Class<? extends Page> page;
    private final int redirectInSeconds;

    public RedirectBehavior(Class<? extends Page> page, int redirectInSeconds) {
        this.page = page;
        this.redirectInSeconds = redirectInSeconds;
    }

    @Override
    public void renderHead(Component component, IHeaderResponse response) {
        response.renderString(String.format("<meta http-equiv='refresh' content='%d;URL=%s' />", redirectInSeconds,
                RequestCycle.get().urlFor(page, null)));
    }
}

This way you can pass the return value from getHomePage() directly - no need for newInstance():

public class PageExpiredPage extends YourBasePage {
    public PageExpiredPage () {
        add(new RedirectBehavior(Application.get().getHomePage(), 5));
    }
}