Unwanted redrawing of view components

First off, let me say I’m new to Vaadin so please forgive me if I’m missing something really obvious.

I’m designing a mock e-shop type application to try and learn the basics of Vaadin and EJBs, but I’ve hit a problem using the Navigator. I’m using views to direct users around the application, but for some reason when I click ‘back’ in my browser the last view redraws the components. The same happens if I change alter the URI fragment - the default view redraws the component each time. Here’s my code:

My UI class:

public class TestShopUI extends UI {

    //@WebServlet(value = "/*", asyncSupported = true)
    @VaadinServletConfiguration(productionMode = false, ui = TestShopUI.class)
    public static class Servlet extends VaadinServlet {
    CDIViewProvider cdiViewProvider;
    protected void init(VaadinRequest request) {
        // Create navigator and add provider
        Navigator navigator = new Navigator(this, this);

A simple login page that swaps the view when the submit button is clicked:

class Login extends VerticalLayout implements View {
    private TextField username;
    Validator validator;
    public void enter(ViewChangeEvent event) {

        Panel panel = new Panel();
        username = new TextField("Username:");
        Button submit = new Button("Submit", new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
        FormLayout content = new FormLayout();
        setComponentAlignment(panel, Alignment.MIDDLE_CENTER);

The main page, empty thusfar:

class Main extends VerticalLayout implements View {
    public void enter(ViewChangeEvent event) {

Could someone please help me to understand why when I get to ‘Main’ and click back, the login page components are drawn again underneath. Do I need to clear the view before I add components and, if so, how do I do that? Thanks in advance.

The views returned by CDIViewProvider are “persistent”; a new instance is not created every time the view is navigated to. So each time navigation happens, the enter() method is called again for the same instance, which ends up adding more components to the layout. So yes, you can either call the removeAllComponents() method in your enter() method before rebuilding the UI, or perhaps preferably, depending on the exact situation, build the view UI once in the view’s default constructor, and reset its state (data displayed etc.) in enter().

That makes perfect sense. Thank you for the clear and concise reply.