Creating an application that preserves state on refresh

By default, Vaadin 7 does not preserve UI state when the browser page is refreshed. This means that the instance number in this example is incremented and the text field cleared on every page refresh:

Java

  1. public class CreatingPreserveState extends UI {
  2. private static int instanceCounter = 0;
  3. private final CssLayout content = new CssLayout();
  4. @Override
  5. public void init(VaadinRequest request) {
  6. TextField tf = new TextField("Instance #" + (++instanceCounter));
  7. tf.setImmediate(true);
  8. content.addComponent(tf);
  9. setContent(content);
  10. }
  11. }

You can however modify your application to preserve your UI between page refreshes with the @PreserveOnRefresh annotation like so

Java

  1. @PreserveOnRefresh
  2. public class PreserveStateUI extends UI {
  3. ...
  4. }

If you want to reinitialize some part of your application when the page is refreshed, you can (starting from Vaadin 7.2) override the refresh method in your UI class. This method is called whenever an already initialized UI is refreshed.

Java

  1. @Override
  2. protected void refresh(VaadinRequest request) {
  3. content.addComponent(new Label("UI was refreshed @"
  4. + System.currentTimeMillis()));
  5. }