Docs

Documentation versions (currently viewingVaadin 25)
Documentation translations (currently viewing)

Questa pagina è stata tradotta automaticamente dalla documentazione ufficiale, che si trova in https://vaadin.com/docs. Potrebbe contenere errori, inesattezze, o affermazioni errate. Vaadin non garantisce né rilascia alcuna dichiarazione in merito all’accuratezza, affidabilità, o tempestività della traduzione.

Aggiungere Deep Linking

Utilizzare un route parameter per memorizzare la selezione dell’elemento prodotto.

Nel passaggio precedente, Lei ha aggiunto un layout principale con un menu di navigazione, e ha assegnato al catalogo prodotti il percorso products.

In questo passaggio, Lei aggiungerà il supporto per il deep linking, rendendo possibile condividere e salvare nei preferiti i link ai singoli prodotti.

Aggiungere un Route Parameter

Affinché il deep linking funzioni, l’applicazione deve essere in grado di determinare l’elemento selezionato dal solo URL. Lei otterrà questo risultato includendo l’ID del prodotto come route parameter.

Note
Utilizzo di chiavi interne del database in URL pubblici
Nelle applicazioni in produzione, eviti di esporre direttamente le primary key del database negli URL. ID sequenziali o prevedibili possono essere indovinati, il che può portare ad accessi non autorizzati ai dati se l’autorizzazione non è stata implementata correttamente. Invece, consideri l’utilizzo di un identificatore generato casualmente, rivolto al pubblico (ad esempio, un UUID o NanoID). Questo approccio migliora la sicurezza e rende l’applicazione più a prova di futuro, poiché le modifiche allo schema del database o alla strategia delle chiavi non interromperanno i link esistenti.

Inizi facendo implementare a ProductCatalogView HasUrlParameter<Long>. Già che ci siamo, modifichi le variabili service e grid trasformandole in campi, poiché Le serviranno in seguito quando implementerà il metodo setParameter(). Il codice aggiornato appare così:

Source code
ProductCatalogView.java
package com.example.product;

import com.example.base.ui.ViewTitle;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.masterdetaillayout.MasterDetailLayout;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.notification.NotificationVariant;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.value.ValueChangeMode;
import com.vaadin.flow.router.BeforeEvent;
import com.vaadin.flow.router.HasUrlParameter;
import com.vaadin.flow.router.Menu;
import com.vaadin.flow.router.OptionalParameter;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.router.RouteAlias;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.OptimisticLockingFailureException;

@Route("products")
@RouteAlias("")
@PageTitle("Product Catalog")
@Menu(order = 1, icon = "vaadin:package")
class ProductCatalogView extends MasterDetailLayout implements HasUrlParameter<Long> { 1

    private final ProductCatalogService service;
    private final ProductCatalogGrid grid;

    ProductCatalogView(ProductCatalogService service) {
        this.service = service;

        // Create components
        var title = new ViewTitle("Product Catalog");

        var searchField = new SearchField();

        grid = new ProductCatalogGrid();
        grid.setItemsPageable(pageable -> service
            .findItems(searchField.getValue(), pageable)
        ).setIdentifierProvider(ProductCatalogItem::productId);

        var drawer = new ProductFormDrawer(productDetails -> {
            var saved = service.save(productDetails);
            grid.getDataProvider().refreshAll();
            return saved;
        }, productDetails -> {
            service.delete(productDetails);
            grid.deselectAll();
            grid.getDataProvider().refreshAll();
        }, this::handleException);

        searchField.addValueChangeListener(e ->
                grid.getDataProvider().refreshAll());

        grid.addSelectionListener(e -> {
            var productDetails = e.getFirstSelectedItem()
                .flatMap(item -> service.findDetailsById(item.productId()));
            productDetails.ifPresent(drawer::setProductDetails);
            setDetail(productDetails.isPresent() ? drawer : null);
        });
        addBackdropClickListener(e -> grid.deselectAll());
        addDetailEscapePressListener(e -> grid.deselectAll());

        var addButton = new Button("Add Product", e ->
            new AddProductDialog(
                productDetails -> {
                    var saved = service.save(productDetails);
                    grid.getDataProvider().refreshAll();
                    service.findItemById(saved.getProductId())
                           .ifPresent(grid::select);
                },
                this::handleException
            ).open()
        );

        // Layout view
        setSizeFull();
        setDetailSize("300px");
        setExpandMaster(true);

        var toolbar = new HorizontalLayout();
        toolbar.setWidthFull();
        toolbar.setWrap(true);
        toolbar.addToStart(title, searchField);
        toolbar.addToEnd(addButton);

        var listLayout = new VerticalLayout(toolbar, grid);
        listLayout.setSizeFull();
        grid.setSizeFull();

        setMaster(listLayout);
    }

    private void handleException(RuntimeException exception) {
        if (exception instanceof OptimisticLockingFailureException) {
            new WarningNotification("Another user has edited the same product. "
                + "Please refresh and try again.").open();
        } else if (exception instanceof DuplicateKeyException) {
            new WarningNotification(
                "The SKU is already in use. Please enter another one.").open();
        } else {
            // Delegate to Vaadin's default error handler
            throw exception;
        }
    }

    @Override
    public void setParameter(BeforeEvent event, @OptionalParameter Long productId) { 2
        // To be implemented
    }

    static class SearchField extends TextField {

        SearchField() {
            setPlaceholder("Search");
            setPrefixComponent(VaadinIcon.SEARCH.create());
            setValueChangeMode(ValueChangeMode.LAZY);
        }
    }

    static class WarningNotification extends Notification {

        WarningNotification(String text) {
            super(text, 3000, Position.MIDDLE);
            addThemeVariants(NotificationVariant.WARNING);
        }
    }
}
  1. Implementare HasUrlParameter<Long> per aggiungere alla view un singolo route parameter di tipo Long.

  2. Rendere opzionale il route parameter con l’annotazione @OptionalParameter.

Ora Lei può navigare a http://localhost:8080/products/12, dove 12 è il valore del route parameter. La view non apparirà ancora diversa — Lei sistemerà questo aspetto nel prossimo passaggio.

Selezionare durante la Navigazione

Ora Lei implementerà setParameter() per selezionare nel grid il prodotto corrispondente. Quando non è presente alcun parametro, dovrebbe cancellare la selezione.

Qui non è necessario mostrare il drawer. Selezionare un elemento da codice genera lo stesso evento di selezione di un clic, quindi il listener di selezione che Lei ha aggiunto nel passaggio Show Details mostra il drawer per Lei.

Modifichi il codice di ProductCatalogView come segue:

Source code
ProductCatalogView.java
package com.example.product;

import com.example.base.ui.ViewTitle;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.masterdetaillayout.MasterDetailLayout;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.notification.NotificationVariant;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.value.ValueChangeMode;
import com.vaadin.flow.router.BeforeEvent;
import com.vaadin.flow.router.HasUrlParameter;
import com.vaadin.flow.router.Menu;
import com.vaadin.flow.router.OptionalParameter;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.router.RouteAlias;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.OptimisticLockingFailureException;

import java.util.Optional;

@Route("products")
@RouteAlias("")
@PageTitle("Product Catalog")
@Menu(order = 1, icon = "vaadin:package")
class ProductCatalogView extends MasterDetailLayout implements HasUrlParameter<Long> {

    private final ProductCatalogService service;
    private final ProductCatalogGrid grid;

    ProductCatalogView(ProductCatalogService service) {
        this.service = service;

        // Create components
        var title = new ViewTitle("Product Catalog");

        var searchField = new SearchField();

        grid = new ProductCatalogGrid();
        grid.setItemsPageable(pageable -> service
            .findItems(searchField.getValue(), pageable)
        ).setIdentifierProvider(ProductCatalogItem::productId);

        var drawer = new ProductFormDrawer(productDetails -> {
            var saved = service.save(productDetails);
            grid.getDataProvider().refreshAll();
            return saved;
        }, productDetails -> {
            service.delete(productDetails);
            grid.deselectAll();
            grid.getDataProvider().refreshAll();
        }, this::handleException);

        searchField.addValueChangeListener(e ->
                grid.getDataProvider().refreshAll());

        grid.addSelectionListener(e -> {
            var productDetails = e.getFirstSelectedItem()
                .flatMap(item -> service.findDetailsById(item.productId()));
            productDetails.ifPresent(drawer::setProductDetails);
            setDetail(productDetails.isPresent() ? drawer : null);
        });
        addBackdropClickListener(e -> grid.deselectAll());
        addDetailEscapePressListener(e -> grid.deselectAll());

        var addButton = new Button("Add Product", e ->
            new AddProductDialog(
                productDetails -> {
                    var saved = service.save(productDetails);
                    grid.getDataProvider().refreshAll();
                    service.findItemById(saved.getProductId())
                           .ifPresent(grid::select);
                },
                this::handleException
            ).open()
        );

        // Layout view
        setSizeFull();
        setDetailSize("300px");
        setExpandMaster(true);

        var toolbar = new HorizontalLayout();
        toolbar.setWidthFull();
        toolbar.setWrap(true);
        toolbar.addToStart(title, searchField);
        toolbar.addToEnd(addButton);

        var listLayout = new VerticalLayout(toolbar, grid);
        listLayout.setSizeFull();
        grid.setSizeFull();

        setMaster(listLayout);
    }

    private void handleException(RuntimeException exception) {
        if (exception instanceof OptimisticLockingFailureException) {
            new WarningNotification("Another user has edited the same product. "
                + "Please refresh and try again.").open();
        } else if (exception instanceof DuplicateKeyException) {
            new WarningNotification(
                "The SKU is already in use. Please enter another one.").open();
        } else {
            // Delegate to Vaadin's default error handler
            throw exception;
        }
    }

    @Override
    public void setParameter(BeforeEvent event, @OptionalParameter Long productId) {
        Optional.ofNullable(productId)
            .flatMap(service::findItemById) 1
            .ifPresentOrElse(grid::select, grid::deselectAll); 2
    }

    static class SearchField extends TextField {

        SearchField() {
            setPlaceholder("Search");
            setPrefixComponent(VaadinIcon.SEARCH.create());
            setValueChangeMode(ValueChangeMode.LAZY);
        }
    }

    static class WarningNotification extends Notification {

        WarningNotification(String text) {
            super(text, 3000, Position.MIDDLE);
            addThemeVariants(NotificationVariant.WARNING);
        }
    }
}
  1. Recuperare il ProductCatalogItem che ha l’ID dall’URL.

  2. Selezionare l’elemento nel grid. Se non c’è alcun parametro, o non esiste alcun prodotto con quell’ID, cancellare invece la selezione. Il listener di selezione quindi mostra o nasconde il drawer.

Se ora Lei naviga a http://localhost:8080/products/12, dovrebbe vedere un elemento selezionato nel grid e i suoi dettagli visibili nel drawer. Provi ID prodotto diversi — i dati di test contengono prodotti da 1 a 50. Navigare a http://localhost:8080/products dovrebbe cancellare la selezione e nascondere il drawer.

Aggiungere Metodi di Navigazione

Ora che l’URL controlla la selezione, Lei può navigare verso prodotti specifici da qualsiasi punto dell’applicazione usando UI.navigate(). Per migliorare la leggibilità, Lei creerà due helper methods: uno per aprire un prodotto specifico, e uno per aprire il catalogo senza selezione.

Aggiorni il codice come segue:

Source code
ProductCatalogView.java
package com.example.product;

import com.example.base.ui.ViewTitle;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.masterdetaillayout.MasterDetailLayout;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.notification.NotificationVariant;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.value.ValueChangeMode;
import com.vaadin.flow.router.BeforeEvent;
import com.vaadin.flow.router.HasUrlParameter;
import com.vaadin.flow.router.Menu;
import com.vaadin.flow.router.OptionalParameter;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.router.RouteAlias;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.OptimisticLockingFailureException;

import java.util.Optional;

@Route("products")
@RouteAlias("")
@PageTitle("Product Catalog")
@Menu(order = 1, icon = "vaadin:package")
class ProductCatalogView extends MasterDetailLayout implements HasUrlParameter<Long> {

    private final ProductCatalogService service;
    private final ProductCatalogGrid grid;

    ProductCatalogView(ProductCatalogService service) {
        this.service = service;

        // Create components
        var title = new ViewTitle("Product Catalog");

        var searchField = new SearchField();

        grid = new ProductCatalogGrid();
        grid.setItemsPageable(pageable -> service
            .findItems(searchField.getValue(), pageable)
        ).setIdentifierProvider(ProductCatalogItem::productId);

        var drawer = new ProductFormDrawer(productDetails -> {
            var saved = service.save(productDetails);
            grid.getDataProvider().refreshAll();
            return saved;
        }, productDetails -> {
            service.delete(productDetails);
            grid.deselectAll();
            grid.getDataProvider().refreshAll();
        }, this::handleException);

        searchField.addValueChangeListener(e ->
                grid.getDataProvider().refreshAll());

        grid.addSelectionListener(e -> {
            var productDetails = e.getFirstSelectedItem()
                .flatMap(item -> service.findDetailsById(item.productId()));
            productDetails.ifPresent(drawer::setProductDetails);
            setDetail(productDetails.isPresent() ? drawer : null);
        });
        addBackdropClickListener(e -> grid.deselectAll());
        addDetailEscapePressListener(e -> grid.deselectAll());

        var addButton = new Button("Add Product", e ->
            new AddProductDialog(
                productDetails -> {
                    var saved = service.save(productDetails);
                    grid.getDataProvider().refreshAll();
                    service.findItemById(saved.getProductId())
                           .ifPresent(grid::select);
                },
                this::handleException
            ).open()
        );

        // Layout view
        setSizeFull();
        setDetailSize("300px");
        setExpandMaster(true);

        var toolbar = new HorizontalLayout();
        toolbar.setWidthFull();
        toolbar.setWrap(true);
        toolbar.addToStart(title, searchField);
        toolbar.addToEnd(addButton);

        var listLayout = new VerticalLayout(toolbar, grid);
        listLayout.setSizeFull();
        grid.setSizeFull();

        setMaster(listLayout);
    }

    private void handleException(RuntimeException exception) {
        if (exception instanceof OptimisticLockingFailureException) {
            new WarningNotification("Another user has edited the same product. "
                + "Please refresh and try again.").open();
        } else if (exception instanceof DuplicateKeyException) {
            new WarningNotification(
                "The SKU is already in use. Please enter another one.").open();
        } else {
            // Delegate to Vaadin's default error handler
            throw exception;
        }
    }

    @Override
    public void setParameter(BeforeEvent event, @OptionalParameter Long productId) {
        Optional.ofNullable(productId)
            .flatMap(service::findItemById)
            .ifPresentOrElse(grid::select, grid::deselectAll);
    }

    public static void showProductDetails(long productId) {
        UI.getCurrentOrThrow().navigate(ProductCatalogView.class, productId);
    }

    public static void showProductCatalog() {
        UI.getCurrentOrThrow().navigate(ProductCatalogView.class);
    }

    static class SearchField extends TextField {

        SearchField() {
            setPlaceholder("Search");
            setPrefixComponent(VaadinIcon.SEARCH.create());
            setValueChangeMode(ValueChangeMode.LAZY);
        }
    }

    static class WarningNotification extends Notification {

        WarningNotification(String text) {
            super(text, 3000, Position.MIDDLE);
            addThemeVariants(NotificationVariant.WARNING);
        }
    }
}

Altre classi nel package com.example.product possono chiamare ProductCatalogView.showProductCatalog() per aprire il catalogo, oppure ProductCatalogView.showProductDetails(productId) per saltare a un prodotto specifico. Per ora, Lei utilizzerà questi metodi internamente.

Se Lei seleziona ora un elemento nel grid, il drawer si apre come prima — ma l’URL non cambia. Lei sistemerà questo aspetto nel prossimo passaggio.

La selezione del grid decide ancora cosa mostra il drawer. L’URL deve soltanto seguirla: ogni volta che la selezione cambia, la view dovrebbe navigare verso l’URL corrispondente. L’URL imposta la selezione quando l’utente apre un link, e in seguito segue la selezione. La guida Add a Master-Detail View descrive lo stesso pattern.

Aggiorni il listener di selezione del grid e setParameter() come segue:

Source code
ProductCatalogView.java
package com.example.product;

import com.example.base.ui.ViewTitle;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.masterdetaillayout.MasterDetailLayout;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.notification.NotificationVariant;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.value.ValueChangeMode;
import com.vaadin.flow.router.BeforeEvent;
import com.vaadin.flow.router.HasUrlParameter;
import com.vaadin.flow.router.Menu;
import com.vaadin.flow.router.OptionalParameter;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.router.RouteAlias;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.OptimisticLockingFailureException;

import java.util.Objects;
import java.util.Optional;

@Route("products")
@RouteAlias("")
@PageTitle("Product Catalog")
@Menu(order = 1, icon = "vaadin:package")
class ProductCatalogView extends MasterDetailLayout implements HasUrlParameter<Long> {

    private final ProductCatalogService service;
    private final ProductCatalogGrid grid;

    ProductCatalogView(ProductCatalogService service) {
        this.service = service;

        // Create components
        var title = new ViewTitle("Product Catalog");

        var searchField = new SearchField();

        grid = new ProductCatalogGrid();
        grid.setItemsPageable(pageable -> service
            .findItems(searchField.getValue(), pageable)
        ).setIdentifierProvider(ProductCatalogItem::productId);

        var drawer = new ProductFormDrawer(productDetails -> {
            var saved = service.save(productDetails);
            grid.getDataProvider().refreshAll();
            return saved;
        }, productDetails -> {
            service.delete(productDetails);
            grid.deselectAll();
            grid.getDataProvider().refreshAll();
        }, this::handleException);

        searchField.addValueChangeListener(e ->
                grid.getDataProvider().refreshAll());

        grid.addSelectionListener(e -> {
            var productDetails = e.getFirstSelectedItem()
                .flatMap(item -> service.findDetailsById(item.productId()));
            productDetails.ifPresent(drawer::setProductDetails);
            setDetail(productDetails.isPresent() ? drawer : null);
            e.getFirstSelectedItem()
                .map(ProductCatalogItem::productId)
                .ifPresentOrElse(
                    ProductCatalogView::showProductDetails, 1
                    ProductCatalogView::showProductCatalog 2
                );
        });
        addBackdropClickListener(e -> grid.deselectAll());
        addDetailEscapePressListener(e -> grid.deselectAll());

        var addButton = new Button("Add Product", e ->
            new AddProductDialog(
                productDetails -> {
                    var saved = service.save(productDetails);
                    grid.getDataProvider().refreshAll();
                    service.findItemById(saved.getProductId())
                           .ifPresent(grid::select);
                },
                this::handleException
            ).open()
        );

        // Layout view
        setSizeFull();
        setDetailSize("300px");
        setExpandMaster(true);

        var toolbar = new HorizontalLayout();
        toolbar.setWidthFull();
        toolbar.setWrap(true);
        toolbar.addToStart(title, searchField);
        toolbar.addToEnd(addButton);

        var listLayout = new VerticalLayout(toolbar, grid);
        listLayout.setSizeFull();
        grid.setSizeFull();

        setMaster(listLayout);
    }

    private void handleException(RuntimeException exception) {
        if (exception instanceof OptimisticLockingFailureException) {
            new WarningNotification("Another user has edited the same product. "
                + "Please refresh and try again.").open();
        } else if (exception instanceof DuplicateKeyException) {
            new WarningNotification(
                "The SKU is already in use. Please enter another one.").open();
        } else {
            // Delegate to Vaadin's default error handler
            throw exception;
        }
    }

    @Override
    public void setParameter(BeforeEvent event, @OptionalParameter Long productId) {
        var selectedId = grid.asSingleSelect().getOptionalValue()
            .map(ProductCatalogItem::productId)
            .orElse(null);
        if (Objects.equals(productId, selectedId)) {
            return; 3
        }
        Optional.ofNullable(productId)
            .flatMap(service::findItemById)
            .ifPresentOrElse(grid::select, grid::deselectAll);
    }

    public static void showProductDetails(long productId) {
        UI.getCurrentOrThrow().navigate(ProductCatalogView.class, productId);
    }

    public static void showProductCatalog() {
        UI.getCurrentOrThrow().navigate(ProductCatalogView.class);
    }

    static class SearchField extends TextField {

        SearchField() {
            setPlaceholder("Search");
            setPrefixComponent(VaadinIcon.SEARCH.create());
            setValueChangeMode(ValueChangeMode.LAZY);
        }
    }

    static class WarningNotification extends Notification {

        WarningNotification(String text) {
            super(text, 3000, Position.MIDDLE);
            addThemeVariants(NotificationVariant.WARNING);
        }
    }
}
  1. Impostare il route parameter se esiste un elemento selezionato.

  2. Cancellare il route parameter se non esiste alcuna selezione.

  3. Se il grid ha già questo prodotto selezionato, non c’è nulla da fare. Questo è il caso quando la navigazione proviene dal listener di selezione, quindi setParameter() non recupera un elemento che il grid possiede già.

Se ora Lei seleziona un elemento nel grid, dovrebbe vedere l’URL cambiare. Cancellare la selezione dovrebbe anche rimuovere il parametro dall’URL, e lo stesso accade eliminando il prodotto selezionato. Poiché l’aggiunta di un prodotto lo seleziona, l’URL segue anche quando Lei aggiunge prodotti. L’elemento Product Catalog nel menu rimane evidenziato per tutto il tempo, poiché nel passaggio precedente Lei ha fatto in modo che gli elementi del menu corrispondessero ai percorsi annidati. Anche se Lei sta chiamando UI.navigate(), la pagina non viene ricaricata e l’istanza di ProductCatalogView rimane la stessa. Vaadin nota che Lei si trova già sulla view verso cui sta cercando di navigare, e richiama soltanto setParameter().

Lei potrebbe aver notato due potenziali cicli:

  • Quando l’utente seleziona un prodotto, il listener di selezione naviga, il che chiama setParameter(). Poiché il prodotto è già selezionato, setParameter() ritorna senza fare nulla.

  • Quando l’utente apre un link, setParameter() seleziona il prodotto, e il listener di selezione naviga verso l’URL su cui l’utente si trova già. Vaadin confronta i parametri dell’URL prima di navigare, e non fa nulla se Lei si trova già sulla stessa view con lo stesso parametro.

Ogni chiamata a UI.navigate() aggiunge anche una voce alla cronologia del browser. Poiché la view naviga ogni volta che la selezione cambia, ogni prodotto selezionato dall’utente diventa una voce della cronologia, e lo stesso vale per la cancellazione della selezione. I pulsanti Indietro e Avanti del browser quindi scorrono queste voci. Ogni passaggio chiama setParameter(), che aggiorna la selezione e il drawer, quindi la view corrisponde sempre all’URL. Provi: selezioni tre prodotti uno dopo l’altro, e poi prema il pulsante Indietro tre volte.

Lo svantaggio è che un utente che ha consultato molti prodotti deve premere Indietro molte volte per uscire dal catalogo. Evitare questo significa cambiare l’URL senza aggiungere una voce alla cronologia. UI.navigate() non può farlo, e la History API di livello inferiore che può farlo bypassa il router, quindi questo tutorial mantiene una voce per selezione.== Codice Completo per Questo Passaggio

Se l’applicazione non si comporta come descritto, confronti i Suoi file con questi elenchi. Essi mostrano ogni classe dell’applicazione come dovrebbe apparire alla fine di questo passaggio.

Il step/deep-link branch del repository vaadin/tutorial su GitHub contiene l’intero progetto così com’è alla fine di questo passaggio.

ProductCatalogView.java
Source code
Java
package com.example.product;

import com.example.base.ui.ViewTitle;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.masterdetaillayout.MasterDetailLayout;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.notification.NotificationVariant;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.value.ValueChangeMode;
import com.vaadin.flow.router.BeforeEvent;
import com.vaadin.flow.router.HasUrlParameter;
import com.vaadin.flow.router.Menu;
import com.vaadin.flow.router.OptionalParameter;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.router.RouteAlias;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.OptimisticLockingFailureException;

import java.util.Objects;
import java.util.Optional;

@Route("products")
@RouteAlias("")
@PageTitle("Product Catalog")
@Menu(order = 1, icon = "vaadin:package")
class ProductCatalogView extends MasterDetailLayout implements HasUrlParameter<Long> {

    private final ProductCatalogService service;
    private final ProductCatalogGrid grid;

    ProductCatalogView(ProductCatalogService service) {
        this.service = service;

        // Create components
        var title = new ViewTitle("Product Catalog");

        var searchField = new SearchField();

        grid = new ProductCatalogGrid();
        grid.setItemsPageable(pageable -> service
            .findItems(searchField.getValue(), pageable)
        ).setIdentifierProvider(ProductCatalogItem::productId);

        var drawer = new ProductFormDrawer(productDetails -> {
            var saved = service.save(productDetails);
            grid.getDataProvider().refreshAll();
            return saved;
        }, productDetails -> {
            service.delete(productDetails);
            grid.deselectAll();
            grid.getDataProvider().refreshAll();
        }, this::handleException);

        searchField.addValueChangeListener(e ->
                grid.getDataProvider().refreshAll());

        grid.addSelectionListener(e -> {
            var productDetails = e.getFirstSelectedItem()
                .flatMap(item -> service.findDetailsById(item.productId()));
            productDetails.ifPresent(drawer::setProductDetails);
            setDetail(productDetails.isPresent() ? drawer : null);
            e.getFirstSelectedItem()
                .map(ProductCatalogItem::productId)
                .ifPresentOrElse(
                    ProductCatalogView::showProductDetails,
                    ProductCatalogView::showProductCatalog
                );
        });
        addBackdropClickListener(e -> grid.deselectAll());
        addDetailEscapePressListener(e -> grid.deselectAll());

        var addButton = new Button("Add Product", e ->
            new AddProductDialog(
                productDetails -> {
                    var saved = service.save(productDetails);
                    grid.getDataProvider().refreshAll();
                    service.findItemById(saved.getProductId())
                           .ifPresent(grid::select);
                },
                this::handleException
            ).open()
        );

        // Layout view
        setSizeFull();
        setDetailSize("300px");
        setExpandMaster(true);

        var toolbar = new HorizontalLayout();
        toolbar.setWidthFull();
        toolbar.setWrap(true);
        toolbar.addToStart(title, searchField);
        toolbar.addToEnd(addButton);

        var listLayout = new VerticalLayout(toolbar, grid);
        listLayout.setSizeFull();
        grid.setSizeFull();

        setMaster(listLayout);
    }

    private void handleException(RuntimeException exception) {
        if (exception instanceof OptimisticLockingFailureException) {
            new WarningNotification("Another user has edited the same product. "
                + "Please refresh and try again.").open();
        } else if (exception instanceof DuplicateKeyException) {
            new WarningNotification(
                "The SKU is already in use. Please enter another one.").open();
        } else {
            // Delegate to Vaadin's default error handler
            throw exception;
        }
    }

    @Override
    public void setParameter(BeforeEvent event, @OptionalParameter Long productId) {
        var selectedId = grid.asSingleSelect().getOptionalValue()
            .map(ProductCatalogItem::productId)
            .orElse(null);
        if (Objects.equals(productId, selectedId)) {
            return;
        }
        Optional.ofNullable(productId)
            .flatMap(service::findItemById)
            .ifPresentOrElse(grid::select, grid::deselectAll);
    }

    public static void showProductDetails(long productId) {
        UI.getCurrentOrThrow().navigate(ProductCatalogView.class, productId);
    }

    public static void showProductCatalog() {
        UI.getCurrentOrThrow().navigate(ProductCatalogView.class);
    }

    static class SearchField extends TextField {

        SearchField() {
            setPlaceholder("Search");
            setPrefixComponent(VaadinIcon.SEARCH.create());
            setValueChangeMode(ValueChangeMode.LAZY);
        }
    }

    static class WarningNotification extends Notification {

        WarningNotification(String text) {
            super(text, 3000, Position.MIDDLE);
            addThemeVariants(NotificationVariant.WARNING);
        }
    }
}
ProductCatalogGrid.java
Source code
Java
package com.example.product;

import com.vaadin.flow.component.grid.ColumnTextAlign;
import com.vaadin.flow.component.grid.Grid;

class ProductCatalogGrid extends Grid<ProductCatalogItem> {

    ProductCatalogGrid() {
        addColumn(ProductCatalogItem::name)
            .setHeader("Name")
            .setSortProperty(ProductCatalogItem.SORT_PROPERTY_NAME);
        addColumn(ProductCatalogItem::price)
            .setHeader("Price")
            .setTextAlign(ColumnTextAlign.END)
            .setSortProperty(ProductCatalogItem.SORT_PROPERTY_PRICE);
        addColumn(ProductCatalogItem::description)
            .setHeader("Description")
            .setSortProperty(ProductCatalogItem.SORT_PROPERTY_DESCRIPTION);
        addColumn(ProductCatalogItem::category)
            .setHeader("Category")
            .setSortProperty(ProductCatalogItem.SORT_PROPERTY_CATEGORY);
        addColumn(ProductCatalogItem::brand)
            .setHeader("Brand")
            .setSortProperty(ProductCatalogItem.SORT_PROPERTY_BRAND);
    }
}
ProductCatalogItem.java
Source code
Java
package com.example.product;

import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Table;

import java.math.BigDecimal;

@Table("PRODUCTS")
record ProductCatalogItem(
        @Id long productId,
        String name,
        String description,
        String category,
        String brand,
        BigDecimal price
) {
    static final String SORT_PROPERTY_NAME = "name";
    static final String SORT_PROPERTY_PRICE = "price";
    static final String SORT_PROPERTY_DESCRIPTION = "description";
    static final String SORT_PROPERTY_CATEGORY = "category";
    static final String SORT_PROPERTY_BRAND = "brand";
}
ProductCatalogItemRepository.java
Source code
Java
package com.example.product;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.repository.PagingAndSortingRepository;

import java.util.Optional;

interface ProductCatalogItemRepository
    extends PagingAndSortingRepository<ProductCatalogItem, Long> {

    Optional<ProductCatalogItem> findById(Long id);
    Slice<ProductCatalogItem> findByNameContainingIgnoreCase(String name,
        Pageable pageable);
}
ProductCatalogService.java
Source code
Java
package com.example.product;

import jakarta.validation.Valid;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.List;
import java.util.Optional;

@Service
@Validated
@Transactional(readOnly = true)
class ProductCatalogService {

    private final ProductCatalogItemRepository productCatalogItemRepository;
    private final ProductDetailsRepository productDetailsRepository;

    public ProductCatalogService(
            ProductCatalogItemRepository productCatalogItemRepository,
            ProductDetailsRepository productDetailsRepository) {
        this.productCatalogItemRepository = productCatalogItemRepository;
        this.productDetailsRepository = productDetailsRepository;
    }

    public List<ProductCatalogItem> findItems(String searchTerm,
            Pageable pageable) {
        return productCatalogItemRepository
            .findByNameContainingIgnoreCase(searchTerm, pageable).getContent();
    }

    public Optional<ProductDetails> findDetailsById(Long id) {
        return productDetailsRepository.findById(id);
    }

    public Optional<ProductCatalogItem> findItemById(Long id) {
        return productCatalogItemRepository.findById(id);
    }

    @Transactional
    public ProductDetails save(@Valid ProductDetails productDetails) {
        return productDetailsRepository.save(new ProductDetails(productDetails));
    }

    @Transactional
    public void delete(ProductDetails productDetails) {
        productDetailsRepository.delete(productDetails);
    }
}
ProductDetails.java
Source code
Java
package com.example.product;

import jakarta.validation.constraints.DecimalMax;
import jakarta.validation.constraints.DecimalMin;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.PositiveOrZero;
import jakarta.validation.constraints.Size;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.relational.core.mapping.Table;

import java.math.BigDecimal;
import java.time.LocalDate;

@Table("PRODUCTS")
class ProductDetails {

    @Id
    private Long productId;
    @Version
    private Long version;
    @NotBlank @Size(max = 100)
    private String name;
    @NotBlank @Size(max = 500)
    private String description;
    @NotBlank @Size(max = 100)
    private String category;
    @Size(max = 100)
    private String brand;
    @NotBlank @Size(max = 50)
    private String sku;
    private LocalDate releaseDate;
    @NotNull @PositiveOrZero
    private BigDecimal price;
    @DecimalMin("0") @DecimalMax("100")
    private BigDecimal discount;

    public ProductDetails() {
    }

    public ProductDetails(ProductDetails original) {
        this.productId = original.productId;
        this.version = original.version;
        this.name = original.name;
        this.description = original.description;
        this.category = original.category;
        this.brand = original.brand;
        this.sku = original.sku;
        this.releaseDate = original.releaseDate;
        this.price = original.price;
        this.discount = original.discount;
    }

    public Long getProductId() {
        return productId;
    }

    public Long getVersion() {
        return version;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getSku() {
        return sku;
    }

    public void setSku(String sku) {
        this.sku = sku;
    }

    public LocalDate getReleaseDate() {
        return releaseDate;
    }

    public void setReleaseDate(LocalDate releaseDate) {
        this.releaseDate = releaseDate;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public BigDecimal getDiscount() {
        return discount;
    }

    public void setDiscount(BigDecimal discount) {
        this.discount = discount;
    }
}
ProductDetailsRepository.java
Source code
Java
package com.example.product;

import org.springframework.data.repository.CrudRepository;

interface ProductDetailsRepository
    extends CrudRepository<ProductDetails, Long> {
}
ProductForm.java
Source code
Java
package com.example.product;

import com.vaadin.flow.component.Composite;
import com.vaadin.flow.component.datepicker.DatePicker;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.html.Span;
import com.vaadin.flow.component.textfield.BigDecimalField;
import com.vaadin.flow.component.textfield.TextArea;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.data.validator.BigDecimalRangeValidator;
import org.jspecify.annotations.Nullable;

import java.math.BigDecimal;
import java.util.Optional;

class ProductForm extends Composite<FormLayout>  {

    private final Binder<ProductDetails> binder;

    ProductForm() {
        // Create components
        var nameField = new TextField("Name");
        nameField.setMaxLength(100);
        var descriptionField = new TextArea("Description");
        descriptionField.setMaxLength(500);
        var categoryField = new TextField("Category");
        categoryField.setMaxLength(100);
        var brandField = new TextField("Brand");
        brandField.setMaxLength(100);
        var skuField = new TextField("SKU");
        skuField.setMaxLength(50);
        var releaseDateField = new DatePicker("Release Date");
        var priceField = new BigDecimalField("Price");
        var discountField = new BigDecimalField("Discount");
        discountField.setSuffixComponent(new Span("%"));

        // Layout form
        var layout = getContent();
        layout.add(nameField);
        layout.add(descriptionField);
        layout.add(categoryField);
        layout.add(brandField);
        layout.add(skuField);
        layout.add(releaseDateField);
        layout.add(priceField);
        layout.add(discountField);

        // Bind fields
        binder = new Binder<>();
        binder.forField(nameField)
              .asRequired("Enter name")
              .bind(ProductDetails::getName,
                    ProductDetails::setName);
        binder.forField(descriptionField)
              .asRequired("Enter description")
              .bind(ProductDetails::getDescription,
                    ProductDetails::setDescription);
        binder.forField(categoryField)
              .asRequired("Enter category")
              .bind(ProductDetails::getCategory,
                    ProductDetails::setCategory);
        binder.forField(brandField)
              .bind(ProductDetails::getBrand,
                    ProductDetails::setBrand);
        binder.forField(skuField)
              .asRequired("Enter SKU")
              .bind(ProductDetails::getSku,
                    ProductDetails::setSku);
        binder.forField(releaseDateField)
              .bind(ProductDetails::getReleaseDate,
                    ProductDetails::setReleaseDate);
        binder.forField(priceField)
              .asRequired("Enter price")
              .withValidator(new BigDecimalRangeValidator(
                  "Enter a price of 0 or more", BigDecimal.ZERO, null))
              .bind(ProductDetails::getPrice,
                    ProductDetails::setPrice);
        binder.forField(discountField)
              .withValidator(new BigDecimalRangeValidator(
                  "Enter a discount between 0 and 100",
                  BigDecimal.ZERO, BigDecimal.valueOf(100)))
              .bind(ProductDetails::getDiscount,
                    ProductDetails::setDiscount);
    }

    public void setFormDataObject(@Nullable ProductDetails productDetails) {
        binder.setBean(productDetails);
    }

    public Optional<ProductDetails> getFormDataObject() {
        if (binder.getBean() == null) {
            throw new IllegalStateException("No form data object");
        }
        if (binder.validate().isOk()) {
            return Optional.of(binder.getBean());
        } else {
            return Optional.empty();
        }
    }
}
ProductFormDrawer.java
Source code
Java
package com.example.product;

import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.confirmdialog.ConfirmDialog;
import com.vaadin.flow.component.html.H2;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.Scroller;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;

class ProductFormDrawer extends VerticalLayout {

    @FunctionalInterface
    interface SaveCallback {
        ProductDetails save(ProductDetails productDetails);
    }

    @FunctionalInterface
    interface DeleteCallback {
        void delete(ProductDetails productDetails);
    }

    @FunctionalInterface
    interface ErrorCallback {
        void handleException(RuntimeException e);
    }

    private final SaveCallback saveCallback;
    private final DeleteCallback deleteCallback;
    private final ErrorCallback errorCallback;
    private final ProductForm form;
    private ProductDetails productDetails;

    ProductFormDrawer(SaveCallback saveCallback, DeleteCallback deleteCallback,
                      ErrorCallback errorCallback) {
        this.saveCallback = saveCallback;
        this.deleteCallback = deleteCallback;
        this.errorCallback = errorCallback;

        var header = new H2("Product Details");
        form = new ProductForm();

        var saveButton = new Button("Save", e -> save());
        saveButton.addThemeVariants(ButtonVariant.PRIMARY);
        var deleteButton = new Button("Delete", e -> delete());
        deleteButton.addThemeVariants(ButtonVariant.ERROR);

        add(header);
        add(new Scroller(form));
        add(new HorizontalLayout(saveButton, deleteButton));
        setHeightFull();
    }

    public void setProductDetails(ProductDetails productDetails) {
        this.productDetails = productDetails;
        form.setFormDataObject(productDetails);
    }

    private void save() {
        form.getFormDataObject().ifPresent(productDetails -> {
            try {
                var saved = saveCallback.save(productDetails);
                setProductDetails(saved);
            } catch (RuntimeException e) {
                errorCallback.handleException(e);
            }
        });
    }

    private void delete() {
        new DeleteProductDialog(() -> {
            try {
                deleteCallback.delete(productDetails);
            } catch (RuntimeException e) {
                errorCallback.handleException(e);
            }
        }).open();
    }

    static class DeleteProductDialog extends ConfirmDialog {

        DeleteProductDialog(Runnable onDelete) {
            super("Delete Product",
                "Are you sure you want to permanently delete this product?",
                "Delete", e -> onDelete.run());
            setCancelable(true);
            setConfirmButtonTheme("error primary");
        }
    }
}
AddProductDialog.java
Source code
Java
package com.example.product;

import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.dialog.Dialog;

class AddProductDialog extends Dialog {

    @FunctionalInterface
    interface SaveCallback {
        void save(ProductDetails productDetails);
    }

    @FunctionalInterface
    interface ErrorCallback {
        void handleException(RuntimeException e);
    }
    private final SaveCallback saveCallback;
    private final ErrorCallback errorCallback;
    private final ProductForm form;

    AddProductDialog(SaveCallback saveCallback, ErrorCallback errorCallback) {
        this.saveCallback = saveCallback;
        this.errorCallback = errorCallback;

        // Create components
        form = new ProductForm();
        form.setFormDataObject(new ProductDetails());
        var saveButton = new Button("Save", e -> save());
        saveButton.addThemeVariants(ButtonVariant.PRIMARY);
        var cancelButton = new Button("Cancel", e -> close());

        // Layout dialog
        setHeaderTitle("Add Product");
        add(form);
        getFooter().add(cancelButton, saveButton);
    }

    private void save() {
        form.getFormDataObject().ifPresent(productDetails -> {
            try {
                saveCallback.save(productDetails);
                close();
            } catch (RuntimeException e) {
                errorCallback.handleException(e);
            }
        });
    }
}
MainLayout.java
Source code
Java
package com.example.base.ui;

import com.vaadin.flow.component.Unit;
import com.vaadin.flow.component.applayout.AppLayout;
import com.vaadin.flow.component.avatar.Avatar;
import com.vaadin.flow.component.avatar.AvatarVariant;
import com.vaadin.flow.component.html.Span;
import com.vaadin.flow.component.icon.Icon;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.Scroller;
import com.vaadin.flow.component.orderedlayout.ScrollerVariant;
import com.vaadin.flow.component.sidenav.SideNav;
import com.vaadin.flow.component.sidenav.SideNavItem;
import com.vaadin.flow.router.Layout;
import com.vaadin.flow.server.menu.MenuConfiguration;

@Layout
class MainLayout extends AppLayout {

    MainLayout() {
        var scroller = new Scroller(new MainMenu());
        scroller.addThemeVariants(ScrollerVariant.OVERFLOW_INDICATORS);

        setPrimarySection(Section.DRAWER);
        addToDrawer(new DrawerHeader(), scroller);
    }

    static class DrawerHeader extends HorizontalLayout {

        DrawerHeader() {
            var appLogo = new Avatar("Click & Collect");
            appLogo.addClassName("app-logo");
            appLogo.addThemeVariants(AvatarVariant.AURA_FILLED, AvatarVariant.XSMALL);

            var appName = new Span("Click & Collect");
            appName.addClassName("app-name");

            add(appLogo, appName);
            setAlignItems(Alignment.CENTER);
            setPadding(true);
        }
    }

    static class MainMenu extends SideNav {

        MainMenu() {
            setMinWidth(200, Unit.PIXELS);
            MenuConfiguration.getMenuEntries().forEach(entry -> {
                var item = new SideNavItem(entry.title(), entry.menuClass(),
                    new Icon(entry.icon()));
                item.setMatchNested(true);
                addItem(item);
            });
        }
    }
}
ViewTitle.java
Source code
Java
package com.example.base.ui;

import com.vaadin.flow.component.Composite;
import com.vaadin.flow.component.applayout.DrawerToggle;
import com.vaadin.flow.component.html.H1;
import com.vaadin.flow.component.orderedlayout.FlexComponent;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;

public class ViewTitle extends Composite<HorizontalLayout> {

    public ViewTitle(String title) {
        addClassName("view-title");

        var layout = getContent();
        layout.add(new DrawerToggle(), new H1(title));
        layout.setAlignItems(FlexComponent.Alignment.CENTER);
    }
}
OrdersView.java
Source code
Java
package com.example.order;

import com.example.base.ui.ViewTitle;
import com.vaadin.flow.component.html.Paragraph;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Menu;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;

@Route("orders")
@PageTitle("Orders")
@Menu(order = 2, icon = "vaadin:cart")
class OrdersView extends VerticalLayout {

    OrdersView() {
        add(new ViewTitle("Orders"));
        add(new Paragraph("Customer orders will be listed here."));
    }
}

Passi Successivi

Ora Lei ha aggiunto il supporto per collegarsi e aggiungere ai preferiti singoli elementi di prodotto. Come esercizio aggiuntivo, Lei potrebbe leggere la guida Query Parameters e provare a memorizzare il valore del campo di ricerca in un parametro di query.

Successivamente, Lei scriverà test automatizzati per il service e la view. Prosegua con il passaggio Add Tests per continuare il tutorial.