Search code examples
vaadincustom-componentvaadin-session

VaadinSession attribute and updating session-bound components


I have a Vaadin Navigator with multiple View elements. Each view has a different purpose however some also contain common traits that I have put inside custom components.

One of those custom components is the menu - it is positioned at the top and allows navigation between the different views. I create and add this component inside the constructor of each view (if you are interested in the menu's implementation see the end of this post). Here is a skeleton for each custom view:

class MyViewX implements View {

  MenuViewComponent mvc;

  public MyViewX() {
    mvc = new MenuViewComponent();
    addComponent(mvc);
  }

  @Override
  public void enter(ViewChangeEvent event) {
  }
}

So far, so good. In order to make things simple I will explain my problem using a simple label and not one of my other custom components but the dependency that I will describe here is the same for those components just like with the label.

Let's say I have a label which sole purpose is to display a greeting with the user's username. In order to do that I use VaadinSession where I store the attribute. This is done by my LoginController, which validates the user by looking into a database and if the user is present, the attribute is set and one of the views is opened automatically. The problem is that VaadinSession.getCurrent().getAttribute("username") returns null when called inside the constructor. This of course makes sense omho because a constructor should not be bound by a session-attribute.

So far I have managed to use the enter() method where there is no problem in retrieving session attributes:

class MyViewX implements View {

  MenuViewComponent mvc;

  public MyViewX() {
    mvc = new MenuViewComponent();
    addComponent(mvc);
  }

  @Override
  public void enter(ViewChangeEvent event) {
    String username = (String)VaadinSession.getCurrent().getAttribute("username");
    Label greeting = new Label("Hello " + username);
    addComponent(greeting);
  }
}

The issue that comes from this is obvious - whenever I open the view where this label is present, a new label is added so if I re-visit the view 10 times, I will get 10 labels. Even if I move the label to be a class member variable the addComponent(...) is the one that screws things up. Some of my custom components really depend on the username attribute (in order to display user-specific content) hence I also have to place those in the enter(...) method. The addComponent(...) makes a mess out of it. I even tried the dirty way of removing a component and then re-adding it alas! in vain:

class MyViewX implements View {

  MenuViewComponent mvc;
  Label greeting;

  public MyViewX() {
    mvc = new MenuViewComponent();
    addComponent(mvc);
  }

  @Override
  public void enter(ViewChangeEvent event) {
    String username = (String)VaadinSession.getCurrent().getAttribute("username");
    greeting = new Label("Hello " + username);

    // Remove if present
    try { removeComponent(greeting); }
    catch(Exception ex) { }

    // Add again but with new content
    addComponent(greeting);
  }
}

but it's still not working. So my question is: what is the simplest way of updating a component that requires session-bound attributes?

The navigation via the menu custom component is omho not the issue here since all components of the menu are loaded in it's constructor. That's why it's also load that component in particular in a view's own constructor. Here is an example of a button in my menu that opens a view:

@SuppressWarnings("serial")
@PreserveOnRefresh
public class MenuViewComponent extends CustomComponent {
  public MenuViewComponent(boolean adminMode) {
    HorizontalLayout layout = new HorizontalLayout();
    Label title = new Label("<h2><b>Vaadin Research Project</b></h2>");
    title.setContentMode(ContentMode.HTML);
    layout.addComponent(title);
    layout.setComponentAlignment(title, Alignment.TOP_LEFT);

    Button personalDashboardButton = new Button("Personal dashboard", new Button.ClickListener() {
      @Override
      public void buttonClick(ClickEvent event) {
        getUI().getNavigator().navigateTo(MainController.PERSONALDASHBOARDVIEW);
      }
    });

    personalDashboardButton.setStyleName(BaseTheme.BUTTON_LINK);
    layout.addComponent(personalDashboardButton);
    layout.setComponentAlignment(personalDashboardButton, Alignment.TOP_CENTER);

    // Add other buttons for other views

    layout.setSizeUndefined();
    layout.setSpacing(true);
    setSizeUndefined();
    setCompositionRoot(layout);
  }
}

PERSONALDASHBOARDVIEW is just one of the many views I have.


Solution

  • It may be worth considering how long should your view instances "live", just as long they're displayed, until the session ends or a mix of the two. With this in mind and depending on what needs to happen when you enter/re-enter a view, you have at least the following 3 options:

    1) Recreate the whole view (allowing for early view garbage-collection)

    • first register a ClassBasedViewProvider (instead of a StaticViewProvider) which does not hold references to the created views:

      navigator = new Navigator(this, viewDisplay);
      navigator.addProvider(new Navigator.ClassBasedViewProvider(MyView.NAME, MyView.class));
      
    • simple view implementation

      public class MyView extends VerticalLayout implements View {
      
          public static final String NAME = "myViewName";
      
          @Override
          public void enter(ViewChangeListener.ViewChangeEvent event) {
              // initialize tables, charts and all the other cool stuff
              addComponent(new SweetComponentWithLotsOfStuff());
          }
      }
      

    2) Keep some already created components and replace others

    public class MyView extends VerticalLayout implements View {
    
        private MySweetComponentWithLotsOfStuff mySweetComponentWithLotsOfStuff;
    
        public MyView() {
            // initialize only critical stuff here or things that don't change on enter
            addComponent(new MyNavigationBar());
        }
    
        @Override
        public void enter(ViewChangeListener.ViewChangeEvent event) {
            // oh, so the user does indeed want to see stuff. great, let's do some cleanup first
            removeComponent(mySweetComponentWithLotsOfStuff);
    
            // initialize tables, charts and all the other cool stuff
            mySweetComponentWithLotsOfStuff = new SweetComponentWithLotsOfStuff();
    
            // show it
            addComponent(mySweetComponentWithLotsOfStuff);
        }
    }
    

    3) Lazy creating and updating (or not) the content when entering

    public class MyView extends VerticalLayout implements View {
    
        private boolean isFirstDisplay = true;
        private MySweetComponentWithLotsOfStuff mySweetComponentWithLotsOfStuff;
    
        public MyView() {
            // initialize only critical stuff here, as the user may not even see this view
        }
    
        @Override
        public void enter(ViewChangeListener.ViewChangeEvent event) {
            // oh, so the user does indeed want to see stuff
            if (isFirstDisplay) {
                isFirstDisplay = false;
                // lazily initialize tables, charts and all the other cool stuff
                mySweetComponentWithLotsOfStuff = new SweetComponentWithLotsOfStuff();
                addComponent(mySweetComponentWithLotsOfStuff);
            } else {
                // maybe trigger component updates, or simply don't do anything
                mySweetComponentWithLotsOfStuff.updateWhateverIsRequired();
            }
        }
    }
    

    I'm sure (and curious) that there may be other options, but I've mainly used a variation of 1) using spring with prototype views and component tabs.