Ajouter le deep linking
- Ajouter un paramètre de route
- Sélectionner lors de la navigation
- Ajouter des méthodes de navigation
- Naviguer lors de la sélection
- Étapes suivantes
À l’étape précédente, vous avez ajouté une mise en page principale avec un menu de navigation, et vous avez donné au catalogue de produits le chemin products.
Dans cette étape, vous allez ajouter la prise en charge du deep linking, ce qui rend possible le partage et l’ajout aux favoris de liens vers des produits individuels.
Ajouter un paramètre de route
Pour que le deep linking fonctionne, l’application doit être capable de déterminer l’élément sélectionné à partir de l’URL seule. Vous allez y parvenir en incluant l’ID du produit en tant que paramètre de route.
|
Note
|
Utiliser des clés internes de base de données dans des URL publiques
Dans les applications en production, évitez d’exposer directement les clés primaires de base de données dans les URL. Des ID séquentiels ou prévisibles peuvent être devinés, ce qui peut conduire à un accès non autorisé aux données si l’autorisation n’a pas été implémentée correctement. À la place, envisagez d’utiliser un identifiant généré aléatoirement, destiné au public (par exemple, un UUID ou NanoID). Cette approche améliore la sécurité et rend l’application plus pérenne, car les changements du schéma de base de données ou de la stratégie de clés ne casseront pas les liens existants.
|
Commencez par faire en sorte que ProductCatalogView implémente HasUrlParameter<Long>. Tant que vous y êtes, changez les variables service et grid en champs, car vous en aurez besoin plus tard lorsque vous implémenterez la méthode setParameter(). Le code mis à jour ressemble à ceci :
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);
}
}
}-
Implémenter
HasUrlParameter<Long>pour ajouter un seul paramètre de route de typeLongà la vue. -
Rendre le paramètre de route optionnel avec l’annotation
@OptionalParameter.
Vous pouvez maintenant naviguer vers http://localhost:8080/products/12, où 12 est la valeur du paramètre de route. La vue n’aura pas encore l’air différente — vous corrigerez cela ensuite.
Sélectionner lors de la navigation
Vous allez maintenant implémenter setParameter() pour sélectionner le produit correspondant dans la grille. Lorsqu’il n’y a pas de paramètre, cela doit effacer la sélection.
Vous n’avez pas besoin d’afficher le tiroir ici. Sélectionner un élément depuis le code déclenche le même événement de sélection qu’un clic, donc le listener de sélection que vous avez ajouté à l’étape Show Details affiche le tiroir pour vous.
Modifiez le code de ProductCatalogView comme suit :
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);
}
}
}-
Récupérer le
ProductCatalogItemqui a l’ID provenant de l’URL. -
Sélectionner l’élément dans la grille. S’il n’y a pas de paramètre, ou pas de produit avec cet ID, effacer la sélection à la place. Le listener de sélection affiche ou masque ensuite le tiroir.
Si vous naviguez maintenant vers http://localhost:8080/products/12, vous devriez voir un élément sélectionné dans la grille et ses détails visibles dans le tiroir. Essayez différents ID de produit — les données de test contiennent des produits de 1 à 50. Naviguer vers http://localhost:8080/products devrait effacer la sélection et masquer le tiroir.
Ajouter des méthodes de navigation
Maintenant que l’URL contrôle la sélection, vous pouvez naviguer vers des produits spécifiques depuis n’importe où dans l’application en utilisant UI.navigate(). Pour améliorer la lisibilité, vous allez créer deux méthodes d’assistance : une pour ouvrir un produit spécifique, et une pour ouvrir le catalogue sans sélection.
Mettez à jour le code comme suit :
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);
}
}
}D’autres classes dans le package com.example.product peuvent appeler ProductCatalogView.showProductCatalog() pour ouvrir le catalogue, ou ProductCatalogView.showProductDetails(productId) pour aller directement à un produit spécifique. Pour l’instant, vous utiliserez ces méthodes en interne.
Naviguer lors de la sélection
Si vous sélectionnez un élément dans la grille maintenant, le tiroir s’ouvre comme avant — mais l’URL ne change pas. Vous allez corriger cela ensuite.
La sélection de la grille décide toujours de ce que le tiroir affiche. L’URL doit seulement la suivre : chaque fois que la sélection change, la vue doit naviguer vers l’URL correspondante. L’URL définit la sélection lorsque l’utilisateur ouvre un lien, puis suit la sélection après cela. Le guide Add a Master-Detail View décrit le même modèle.
Mettez à jour le listener de sélection de la grille et setParameter() comme suit :
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);
}
}
}-
Définir le paramètre de route s’il y a un élément sélectionné.
-
Effacer le paramètre de route s’il n’y a pas de sélection.
-
Si la grille a déjà ce produit sélectionné, il n’y a rien à faire. C’est le cas lorsque la navigation provient du listener de sélection, donc
setParameter()ne récupère pas un élément que la grille possède déjà.
Si vous sélectionnez maintenant un élément dans la grille, vous devriez voir l’URL changer. Effacer la sélection devrait aussi supprimer le paramètre d’URL, et c’est également le cas lors de la suppression du produit sélectionné. Comme l’ajout d’un produit le sélectionne, l’URL suit aussi lorsque vous ajoutez des produits. L’élément Product Catalog dans le menu reste surligné tout du long, puisque vous avez fait en sorte que les éléments de menu correspondent aux chemins imbriqués à l’étape précédente. Même si vous appelez UI.navigate(), la page ne se recharge pas et l’instance de ProductCatalogView reste la même. Vaadin remarque que vous êtes déjà sur la vue vers laquelle vous essayez de naviguer, et appelle seulement setParameter() à nouveau.
Vous avez peut-être remarqué deux boucles potentielles :
-
Lorsque l’utilisateur sélectionne un produit, le listener de sélection navigue, ce qui appelle
setParameter(). Comme le produit est déjà sélectionné,setParameter()retourne sans rien faire. -
Lorsque l’utilisateur ouvre un lien,
setParameter()sélectionne le produit, et le listener de sélection navigue vers l’URL sur laquelle l’utilisateur se trouve déjà. Vaadin compare les paramètres d’URL avant de naviguer, et ne fait rien si vous êtes déjà sur la même vue avec le même paramètre.
Chaque appel à UI.navigate() ajoute également une entrée à l’historique du navigateur. Comme la vue navigue chaque fois que la sélection change, chaque produit que l’utilisateur sélectionne devient une entrée d’historique, et l’effacement de la sélection aussi. Les boutons Précédent et Suivant du navigateur parcourent ensuite ces entrées. Chaque étape appelle setParameter(), qui met à jour la sélection et le tiroir, de sorte que la vue correspond toujours à l’URL. Essayez : sélectionnez trois produits l’un après l’autre, puis appuyez trois fois sur le bouton Précédent.
L’inconvénient est qu’un utilisateur qui a consulté de nombreux produits doit appuyer sur Précédent de nombreuses fois pour quitter le catalogue. Éviter cela signifie changer l’URL sans ajouter d’entrée d’historique. UI.navigate() ne peut pas faire cela, et l’History API de plus bas niveau qui le peut contourne le routeur, donc ce tutoriel conserve une entrée par sélection.== Code complet pour cette étape
Si votre application ne se comporte pas comme décrit, comparez vos fichiers avec ces listes. Elles montrent chaque classe de l’application telle qu’elle doit apparaître à la fin de cette étape.
La step/deep-link branch du dépôt vaadin/tutorial sur GitHub contient l’intégralité du projet tel qu’il se présente à la fin de cette étape.
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."));
}
}Étapes suivantes
Vous avez maintenant ajouté la prise en charge des liens vers et des signets pour des éléments de produit individuels. En exercice supplémentaire, vous pourriez lire le guide Query Parameters et essayer de stocker la valeur du champ de recherche dans un paramètre de requête.
Ensuite, vous écrirez des tests automatisés pour le service et la vue. Passez à l’étape Add Tests pour continuer le tutoriel.