Vaadin Web UI Guide to Building Interfaces in Pure Java
Build a Vaadin web UI in Java: views, layouts, Binder forms, lazy Grids, push updates, security, testing and the production build in one worked app.

Most Java developers who need a web interface face the same fork. Learn a second ecosystem (a JavaScript framework, a build chain, a REST contract between two codebases and two sets of tests), or generate server-rendered pages and live with the limits of forms and page reloads. Vaadin Flow takes a third route: you write the interface in Java, with components such as TextField, Grid and Dialog, and a thin client in the browser draws them. There is no DOM code, no JSON endpoints between your UI and your service layer, and no second language. For internal tools, admin consoles, back-office applications and data-heavy dashboards, that is a large amount of work you do not do.
This guide builds one application from nothing and covers the whole life of a Vaadin project: the server-side model and why it shapes everything, views and routing, layouts, forms with validation, a lazily loaded Grid, dialogs, theming, push updates, security, testing, memory and the production build. The application is a small customer manager on Spring Boot 4 and Java 25 with Vaadin 25. Where a topic has its own post, the section links to it for the deeper treatment, so use this page as the map. The example code compiles against the Flow APIs named in each section, but verify details against the Vaadin documentation for your exact version, since component APIs gain methods between releases.
How Vaadin Flow works
Everything else in this guide follows from one fact: the component tree lives on the server. When your code calls new Button("Save"), an object is created in the JVM, in the user's session. Vaadin sends a description of that object to the browser, where a small JavaScript client renders it as web components. When the user clicks, the client sends an event to the server, your Java listener runs, you change some components, and Vaadin sends back only what changed. The browser holds a rendering, not the application state. The long version is in how the Flow server-side model works.
This design has consequences you should hold in mind from the start:
| Consequence | What it means for you |
|---|---|
| Your listener code runs on the server | It can call services, repositories and security checks directly; there is no API layer to design |
| State lives in a session | Memory grows with concurrent users, see the memory section below |
| Every interaction is a round trip | A slow server call makes the UI feel slow; keep listeners fast and move long work to background threads |
| The client is generic | Nothing about your business rules exists in the browser, which is also a security benefit |
| Components are Java objects | You can refactor, test and reuse a UI with the tools you use for any Java code |
Vaadin also offers Hilla, a variant where the UI is written in React and talks to typed endpoints, covered in Hilla with React. Everything below is Flow. If your team writes React already, ask whether you want this at all, see Vaadin against React and Spring Boot.
Set up the project
Start from start.vaadin.com or generate a Spring Boot project and add the Vaadin starter. The pieces that matter in pom.xml are the BOM, the Spring Boot starter and the production profile:
<properties>
<java.version>25</java.version>
<vaadin.version>25.0.0</vaadin.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-bom</artifactId>
<version>${vaadin.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>production</id>
<build>
<plugins>
<plugin>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-maven-plugin</artifactId>
<version>${vaadin.version}</version>
<executions>
<execution>
<goals>
<goal>build-frontend</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>Run ./mvnw spring-boot:run, open http://localhost:8080, and the first start downloads and compiles the frontend, which takes a minute. Later starts are fast. The Spring wiring (beans in views, scopes, security integration) is in Vaadin with Spring Boot, and a shorter first-hour walkthrough is in the beginners tutorial.
The data model for the example is one entity and a repository:
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
@Entity
public class Customer {
@Id @GeneratedValue
private Long id;
@NotBlank @Size(max = 80)
private String name;
@NotBlank @Email
private String email;
private String tier = "STANDARD";
public Long getId() { return id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getTier() { return tier; }
public void setTier(String tier) { this.tier = tier; }
}import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CustomerRepository extends JpaRepository<Customer, Long> {
Page<Customer> findByNameContainingIgnoreCase(String name, Pageable pageable);
long countByNameContainingIgnoreCase(String name);
}A thin service sits between the views and the repository. Views should never touch repositories directly in a real application, because the service is where transactions and security belong:
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional(readOnly = true)
public class CustomerService {
private final CustomerRepository repository;
public CustomerService(CustomerRepository repository) {
this.repository = repository;
}
public Page<Customer> search(String filter, Pageable page) {
return repository.findByNameContainingIgnoreCase(filter == null ? "" : filter, page);
}
public long count(String filter) {
return repository.countByNameContainingIgnoreCase(filter == null ? "" : filter);
}
@Transactional
public Customer save(Customer customer) {
return repository.save(customer);
}
@Transactional
public void delete(Customer customer) {
repository.delete(customer);
}
}A view is a Java class
A page in Vaadin is a component class with a @Route. This is the whole definition of a page that greets the user:
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
@Route("hello")
@PageTitle("Hello")
public class HelloView extends VerticalLayout {
public HelloView() {
TextField name = new TextField("Your name");
Button greet = new Button("Greet", event -> Notification.show("Hello, " + name.getValue()));
add(name, greet);
}
}Open /hello, type a name and click: a notification appears, and your Java lambda ran on the server. Notice what is absent. There is no controller, no template, no JSON and no JavaScript. VerticalLayout is a container that stacks its children, and add appends components. Button takes a click listener as a lambda. That is the programming model for everything else.
A few rules that save time:
- Views are created per navigation. Each visit constructs a new instance, so instance fields are per-user, per-visit state. Do not store shared data in them.
- Do the setup in the constructor, load data in lifecycle hooks. If you need route parameters or want to refresh on re-entry, implement
BeforeEnterObserveror overrideonAttach. - Components are cheap, listeners are the cost. Create as many components as the interface needs, but do not call a database inside a render loop.
Layouts give pages a shared frame
Most applications have a header and navigation around the page content. In Vaadin that frame is a layout: a component that implements RouterLayout, and pages declare it with @Route(value = "...", layout = MainLayout.class). The AppLayout component provides a drawer and navbar:
import com.vaadin.flow.component.applayout.AppLayout;
import com.vaadin.flow.component.applayout.DrawerToggle;
import com.vaadin.flow.component.html.H1;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.sidenav.SideNav;
import com.vaadin.flow.component.sidenav.SideNavItem;
public class MainLayout extends AppLayout {
public MainLayout() {
H1 title = new H1("Customer manager");
title.getStyle().set("font-size", "var(--lumo-font-size-l)").set("margin", "0");
addToNavbar(new DrawerToggle(), title);
SideNav nav = new SideNav();
nav.addItem(new SideNavItem("Customers", CustomerListView.class, VaadinIcon.USERS.create()));
nav.addItem(new SideNavItem("Dashboard", DashboardView.class, VaadinIcon.CHART.create()));
addToDrawer(nav);
}
}SideNavItem takes a view class, not a path string, so renaming a route does not break the menu. The navigation model, nested layouts, route parameters and @RoutePrefix are covered in routing and layouts. One layout can wrap many views, and layouts can nest (a settings layout inside the main layout), which is how you build sections that share a sub-menu.
A list with a filter and a lazy Grid
The Grid is the component most business applications are built around. This view lists customers, with a search field and a button for adding one:
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.grid.GridVariant;
import com.vaadin.flow.component.icon.VaadinIcon;
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.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.spring.data.VaadinSpringDataHelpers;
@Route(value = "", layout = MainLayout.class)
@PageTitle("Customers")
public class CustomerListView extends VerticalLayout {
private final CustomerService service;
private final Grid<Customer> grid = new Grid<>(Customer.class, false);
private final TextField filter = new TextField();
public CustomerListView(CustomerService service) {
this.service = service;
setSizeFull();
filter.setPlaceholder("Filter by name");
filter.setClearButtonVisible(true);
filter.setValueChangeMode(ValueChangeMode.LAZY); // waits ~400 ms after the last key
filter.addValueChangeListener(e -> grid.getDataProvider().refreshAll());
Button add = new Button("Add customer", VaadinIcon.PLUS.create(), e -> openEditor(new Customer()));
add.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
grid.addThemeVariants(GridVariant.LUMO_ROW_STRIPES);
grid.addColumn(Customer::getName).setHeader("Name").setSortable(true).setKey("name");
grid.addColumn(Customer::getEmail).setHeader("Email").setKey("email");
grid.addColumn(Customer::getTier).setHeader("Tier");
grid.addItemDoubleClickListener(e -> openEditor(e.getItem()));
grid.setItems(query -> service.search(
filter.getValue(),
VaadinSpringDataHelpers.toSpringPageRequest(query)).stream());
add(new HorizontalLayout(filter, add), grid);
expand(grid);
}
private void openEditor(Customer customer) {
new CustomerEditor(customer, service, () -> grid.getDataProvider().refreshAll()).open();
}
}The important line is grid.setItems(query -> ...). This overload gives Vaadin a callback instead of a list. The grid asks for exactly the rows the browser is about to show, with an offset, a limit and the sort order, and toSpringPageRequest turns that into a Spring Pageable. A table of five million rows costs the same as one of fifty, because the server only ever loads a screenful. ValueChangeMode.LAZY matters too: without it, the filter would query on every keystroke. The pitfalls of lazy loading, such as counting, sorting by a nested property and stale pages, are in lazy loading in the Grid.
When the dataset is small, a plain grid.setItems(list) is fine and simpler. Choose the callback form when the table can grow or when the query is expensive.
Forms with Binder and validation
Forms are where server-side UI frameworks usually get tedious. Binder handles the repetitive part: it connects fields to bean properties, converts types, validates and reports errors next to the field. BeanValidationBinder reads the Jakarta Validation annotations already on the entity, so the rules live in one place.
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.textfield.EmailField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.BeanValidationBinder;
import com.vaadin.flow.data.binder.ValidationException;
import java.util.List;
public class CustomerEditor extends Dialog {
private final BeanValidationBinder<Customer> binder = new BeanValidationBinder<>(Customer.class);
private final Customer customer;
public CustomerEditor(Customer customer, CustomerService service, Runnable onSaved) {
this.customer = customer;
setHeaderTitle(customer.getId() == null ? "New customer" : "Edit customer");
TextField name = new TextField("Name");
EmailField email = new EmailField("Email");
ComboBox<String> tier = new ComboBox<>("Tier", List.of("STANDARD", "GOLD", "PLATINUM"));
binder.forField(name).asRequired("Name is required").bind("name");
binder.forField(email).asRequired("Email is required").bind("email");
binder.forField(tier).bind("tier");
binder.readBean(customer);
add(new FormLayout(name, email, tier));
Button save = new Button("Save", e -> {
try {
binder.writeBean(customer); // validates, then copies into the bean
service.save(customer);
onSaved.run();
close();
Notification.show("Saved");
} catch (ValidationException ex) {
Notification.show("Fix the highlighted fields");
}
});
save.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
getFooter().add(new Button("Cancel", e -> close()), save);
}
}Several things happen that you did not write. Type the wrong email and the EmailField shows the error under the field as you leave it. asRequired adds the required indicator and message. writeBean runs every validator and, on failure, marks each invalid field and throws; on success it copies values into the bean in one step. If you want to copy only when valid and also keep the bean untouched on failure, that is exactly what writeBean does, while writeBeanIfValid returns a boolean instead of throwing. The detail of converters (StringToIntegerConverter), cross-field validators and status labels is in Binder validation for forms.
One design rule: validate in the entity or service as well. Binder validation is a convenience for the user. A server-side check in the service is what protects the data when another caller reaches it.
Add a dashboard and a chart
A second view shows how views share services. It also uses only built-in components:
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.H2;
import com.vaadin.flow.component.html.Span;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
@Route(value = "dashboard", layout = MainLayout.class)
@PageTitle("Dashboard")
public class DashboardView extends VerticalLayout {
public DashboardView(CustomerService service) {
add(new H2("Overview"), stat("Customers", String.valueOf(service.count(""))));
}
private Div stat(String label, String value) {
Span number = new Span(value);
number.getStyle().set("font-size", "var(--lumo-font-size-xxxl)").set("font-weight", "600");
Span caption = new Span(label);
caption.getStyle().set("color", "var(--lumo-secondary-text-color)");
Div box = new Div(number, new Div(caption));
box.getStyle().set("padding", "var(--lumo-space-m)")
.set("border", "1px solid var(--lumo-contrast-10pct)")
.set("border-radius", "var(--lumo-border-radius-l)");
return box;
}
}The styles use Lumo custom properties, the design tokens of Vaadin's default theme, so the card follows the theme including dark mode. For real charts, Vaadin has a Charts component, see charts and dashboards.
Theming
Vaadin ships a theme called Lumo with a light and a dark variant, and every component exposes theme variants (ButtonVariant.LUMO_PRIMARY) and CSS custom properties (--lumo-primary-color). The practical rules for keeping a theme maintainable:
- Change tokens, not components. Redefine
--lumo-primary-colorand spacing once, and every component follows. - Prefer theme variants to custom CSS.
LUMO_ERRORandLUMO_SMALLare supported and survive upgrades. - Put one-off layout CSS in a style sheet attached to the view or app, not in
getStyle().set()calls scattered across Java. The inline calls above are acceptable in small doses, and a maintenance cost in bulk.
The mechanics of attaching a theme, with the changes in recent versions, are in theming and styling, and the list of changes in the current major version is in what is new in Vaadin 25.
Updating the UI from another thread
A UI is single-threaded per session: Vaadin locks the session while a listener runs. If a background thread wants to change a component, for example when a long report finishes, it must hand the change to the UI. Enable server push on the application class, and use UI.access:
import com.vaadin.flow.component.page.AppShellConfigurator;
import com.vaadin.flow.component.page.Push;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@Push
public class Application implements AppShellConfigurator {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.html.Span;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Route;
import java.util.concurrent.CompletableFuture;
@Route(value = "report", layout = MainLayout.class)
public class ReportView extends VerticalLayout {
public ReportView() {
Span status = new Span("Idle");
Button run = new Button("Run report", e -> {
UI ui = UI.getCurrent(); // capture while on the UI thread
status.setText("Working...");
CompletableFuture.supplyAsync(this::slowReport).thenAccept(result ->
ui.access(() -> status.setText("Done: " + result))); // safe hand-back
});
add(run, status);
}
private String slowReport() {
try { Thread.sleep(3000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); }
return "42 rows";
}
}Capture UI.getCurrent() before leaving the UI thread: on a worker thread it returns null. ui.access acquires the session lock and, with @Push, sends the change immediately. Without push, the update would wait for the next user interaction. Handle the case where the user navigated away: use addDetachListener to cancel the work, or the callback will write to a component that is gone, which is harmless but wasteful. The full treatment, with broadcasters and cleanup, is in server push.
Security
Because the client is generic and listeners run on the server, security is the same as for any Spring application with one important addition: views are reachable by URL. Secure the routes and the services.
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Route;
import jakarta.annotation.security.RolesAllowed;
@Route(value = "admin", layout = MainLayout.class)
@RolesAllowed("ADMIN")
public class AdminView extends VerticalLayout {
}Vaadin integrates with Spring Security through VaadinWebSecurity, which wires login view handling and checks @RolesAllowed, @PermitAll and @AnonymousAllowed on views. Two rules cover most mistakes. First, hiding a menu item is not security; the route must be protected. Second, check authorization in the service layer too (@PreAuthorize), because a view is only one caller. The setup, a login view, role-based menus and CSRF behavior are in securing a Vaadin app with Spring Security.
Test without a browser
Because the UI is Java objects, most of it can be tested as Java. The form rules are the best place to start, since Binder runs without a browser or a server. This test builds the same binder the editor uses and checks that an invalid bean is rejected and a valid one is written:
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.vaadin.flow.component.textfield.EmailField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.BeanValidationBinder;
import org.junit.jupiter.api.Test;
class CustomerBinderTest {
private final BeanValidationBinder<Customer> binder = new BeanValidationBinder<>(Customer.class);
private final TextField name = new TextField();
private final EmailField email = new EmailField();
CustomerBinderTest() {
binder.forField(name).asRequired("Name is required").bind("name");
binder.forField(email).asRequired("Email is required").bind("email");
}
@Test
void rejectsBadEmail() {
name.setValue("Ada");
email.setValue("not-an-email");
assertFalse(binder.writeBeanIfValid(new Customer()));
}
@Test
void writesValidValues() {
name.setValue("Ada");
email.setValue("[email protected]");
Customer c = new Customer();
assertTrue(binder.writeBeanIfValid(c));
assertEquals("[email protected]", c.getEmail());
}
}Vaadin also ships browserless testing support that creates a UI in the JVM so a test can find components, type into fields and click buttons, and the Karibu-Testing library does the same for views. Use them for view logic such as "Save closes the dialog and refreshes the grid". Cover three layers: service tests for business rules, browserless tests for view behavior, and a handful of end-to-end browser tests against the built production jar, which is where problems that only appear with the compiled frontend are found.
Memory: sessions live on the server
The state of every open browser tab sits in the JVM: the component tree, the grid's currently cached rows, the binder, the beans you hold. Memory scales with active users and the size of each UI. Three habits keep it in check:
- Keep data in the database, not in views. A view that loads 50,000 customers into a list holds them for the life of the tab. Use the lazy callback.
- Hold ids, not object graphs. Re-fetch on demand.
- Set the session timeout deliberately and size the heap for concurrent users: if each active UI costs 1 to 3 MB, a thousand concurrent users need 1 to 3 GB for sessions alone, before caches. Measure with a heap dump of a loaded test instance.
The monitoring and sizing approach is in session memory, and the same server-side-state trade-off explains why sticky sessions matter behind a load balancer. For the underlying JVM view of the numbers, see JVM memory areas.
Ship the production build
Development mode compiles the frontend on demand and ships tooling; it must not reach production. The production build bundles and minifies the frontend into the jar. Build with the profile defined above:
./mvnw -Pproduction clean package
java -jar target/crm-1.0.jarA blank white page after deployment is nearly always this step skipped: the app started in development mode in a container with no Node, or the profile never ran. The checklist is in fixing a blank page after a production build, and the bundle options (offline use, CI caching of node_modules, the frontend/generated directory) are in the production bundle. Add three production practices: set vaadin.productionMode=true only through the profile and not by hand, cache the frontend dependencies in CI so builds are not 8 minutes, and test the built jar, not the dev server.
Navigation, parameters and the browser's back button
A Vaadin application is still a web application: each view has a URL, the back button works and a link can be pasted into chat. That only holds if you put state in the URL when it should be there. A detail page for one customer takes the id as a route parameter:
import com.vaadin.flow.component.html.H2;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.BeforeEvent;
import com.vaadin.flow.router.HasUrlParameter;
import com.vaadin.flow.router.NotFoundException;
import com.vaadin.flow.router.Route;
@Route(value = "customers", layout = MainLayout.class)
public class CustomerDetailView extends VerticalLayout implements HasUrlParameter<Long> {
private final CustomerRepository repository;
public CustomerDetailView(CustomerRepository repository) {
this.repository = repository;
}
@Override
public void setParameter(BeforeEvent event, Long id) {
Customer customer = repository.findById(id).orElseThrow(NotFoundException::new);
removeAll();
add(new H2(customer.getName()));
}
}/customers/42 now opens this view with id = 42, and a missing customer produces the router's not-found page instead of a stack trace. Query parameters work for filters: read them with event.getLocation().getQueryParameters() and write them back with UI.getCurrent().navigate(...) so a filtered grid can be bookmarked. The rule of thumb is that anything a user would want to share belongs in the URL, and anything private to the interaction (a half-typed value) stays in the component.
Navigation also has guards. A BeforeEnterObserver can redirect (to login, to a wizard's first step) and a BeforeLeaveObserver can warn about unsaved changes:
@Override
public void beforeLeave(BeforeLeaveEvent event) {
if (binder.hasChanges()) {
BeforeLeaveEvent.ContinueNavigationAction action = event.postpone();
ConfirmDialog dialog = new ConfirmDialog("Discard changes?", "Unsaved edits will be lost.",
"Discard", e -> action.proceed());
dialog.setCancelable(true);
dialog.open();
}
}event.postpone() pauses navigation and returns an action you call to continue. This is the Vaadin counterpart of the browser's "leave site?" prompt, and it is only needed on forms that matter.
Dialogs, notifications and confirming destructive actions
Three small components carry most of the feedback in a business UI. Notification is a transient message, Dialog is a modal container, and ConfirmDialog is a ready-made question with buttons. Use a confirmation before anything destructive, and use a notification for everything else; a dialog for "Saved!" trains users to dismiss dialogs without reading them.
Deleting a customer from the grid's context shows the pattern:
private void confirmDelete(Customer customer) {
ConfirmDialog dialog = new ConfirmDialog();
dialog.setHeader("Delete " + customer.getName() + "?");
dialog.setText("This cannot be undone.");
dialog.setCancelable(true);
dialog.setConfirmText("Delete");
dialog.setConfirmButtonTheme("error primary");
dialog.addConfirmListener(e -> {
service.delete(customer);
grid.getDataProvider().refreshAll();
Notification.show("Deleted " + customer.getName(), 3000, Notification.Position.BOTTOM_START);
});
dialog.open();
}Tell the user what was affected in the confirmation text, and let the notification expire on its own after a few seconds. For errors, show the reason and the next step, never a bare "Error". Unexpected exceptions in a listener reach Vaadin's error handler, which logs them and shows a generic message; replace it with your own to add a correlation id:
VaadinSession.getCurrent().setErrorHandler(event -> {
String id = java.util.UUID.randomUUID().toString().substring(0, 8);
log.error("UI error {}", id, event.getThrowable());
Notification.show("Something went wrong. Reference " + id);
});Support can then find the stack trace from the reference a user reads out.
Building bigger screens from smaller components
A view that grows past two hundred lines is a class that mixes layout, data access and behavior. Vaadin makes extraction easy because a component is just a class that extends a layout. Pull the filter bar out of the list view:
public class CustomerFilterBar extends HorizontalLayout {
private final TextField text = new TextField();
public CustomerFilterBar(Runnable onChange) {
text.setPlaceholder("Filter by name");
text.setValueChangeMode(ValueChangeMode.LAZY);
text.addValueChangeListener(e -> onChange.run());
add(text);
}
public String value() { return text.getValue(); }
}The view passes a callback and reads value(), and the bar can be reused and tested on its own. Three conventions keep a Vaadin codebase tidy as it grows:
- **A component receives what it needs in its constructor and reports events through callbacks or
ComponentEvents.** It does not reach into its parent. - Data access happens in a presenter or service, not in components. A component that calls a repository is untestable without a database.
- Name views for the task, not the entity.
CustomerImportViewandCustomerListViewcan coexist; aCustomerViewthat does everything cannot be split later.
For a widget that has no counterpart in the library, writing a custom component covers wrapping a web component, and a full CRUD application strings these ideas together on a real schema.
Internationalization
If your users read more than one language, build it in from the first view, because retrofitting is a search through every string literal. Vaadin provides I18NProvider, and getTranslation looks up a key for the current locale:
@Component
public class Messages implements I18NProvider {
@Override
public List<Locale> getProvidedLocales() {
return List.of(Locale.ENGLISH, Locale.GERMAN);
}
@Override
public String getTranslation(String key, Locale locale, Object... params) {
ResourceBundle bundle = ResourceBundle.getBundle("messages", locale);
String value = bundle.containsKey(key) ? bundle.getString(key) : "!" + key;
return params.length == 0 ? value : MessageFormat.format(value, params);
}
}Views then call getTranslation("customer.save") instead of writing "Save". The !key fallback makes a missing translation visible during testing instead of throwing. Dates and numbers should go through the locale as well: DatePicker and NumberField respect UI.getLocale().
Performance: what is actually slow
Vaadin applications feel slow for four reasons, in this order of likelihood.
A listener does slow work on the UI thread. The session is locked while a listener runs, so a six second report query freezes that user's UI, including other tabs in the session. Move it off-thread with CompletableFuture and ui.access as in the push section, and show a progress indicator in the meantime.
A grid loads too much. An unbounded findAll() fed to setItems(list) loads the whole table into memory and serializes much of it to the client. Use the lazy callback, and make sure the query is indexed for the sort columns the user can click. A sortable column the database cannot sort quickly is a performance bug waiting for a click.
Too many components. A page with thousands of live components, such as a loop that creates a row of fields per record, is slow to build and slow to synchronize. Use a Grid with renderers, or a virtual list.
The network is far from the server. Every interaction is a round trip, so a user across an ocean from the server feels each one. Reduce chatty interactions: handle ValueChangeMode.ON_BLUR instead of EAGER for fields that do not need instant feedback, and avoid listeners on high-frequency events such as scroll.
Measure before changing. The browser's network panel shows the size and count of the UIDL requests, and a profiler or thread dumps on the server show what a slow listener is doing.
Containers and deployment
A Vaadin production build is an ordinary Spring Boot jar, so it containerizes like any other service. The two details specific to Vaadin are that the build runs the frontend compiler, which needs Node (the plugin downloads one, and the CI cache should hold it), and that sessions are stateful. Behind a load balancer, either use sticky sessions or store sessions in a shared store; without one of them, a user's next request lands on an instance that never saw their UI and receives a session-expired page.
FROM eclipse-temurin:25-jdk AS build
WORKDIR /src
COPY . .
RUN ./mvnw -q -Pproduction -DskipTests package
FROM eclipse-temurin:25-jre
COPY --from=build /src/target/crm-1.0.jar /app/crm.jar
ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75"
ENTRYPOINT ["java", "-jar", "/app/crm.jar"]The build-stage layout is explained in multi-stage Docker builds. Expose a health endpoint through Spring Boot Actuator for the readiness probe, because a Vaadin app that is still compiling its bundle in a misbuilt image answers requests with errors long before a plain TCP check notices.
Upgrading between versions
Vaadin releases a major version about once a year and keeps the previous one supported. Upgrades are mostly mechanical, but plan for them:
- Read the release notes and the migration guide for each major before changing the version number.
- Upgrade the BOM version in one place, then compile; deprecated methods turn into errors one major later, so fix deprecations when they appear.
- Delete
node_modules,package-lock.jsonand the generated frontend folder, then rebuild, since stale generated files are the most common cause of strange errors after an upgrade. - Run the browserless and end-to-end tests before you look at the UI.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Storing shared data in a view's fields | Each navigation creates a new view, so the data disappears or is per-user | Put shared data in a service or a Spring bean with the right scope |
Calling UI.getCurrent() in a background thread | Returns null and a NullPointerException | Capture the UI before leaving the UI thread |
grid.setItems(repository.findAll()) on a big table | Slow page and heavy session memory | Use the lazy setItems(query -> ...) overload |
| Hiding a menu item as the only access control | The route is still reachable by URL | Annotate the view and the service |
| Running the dev build in production | Blank page or slow first load | Build with the production profile |
| Creating components in a loop per record | Thousands of live components | Use a Grid with a component renderer for the few rows that need one |
| Ignoring session timeouts in testing | Users report sudden "session expired" | Test with a short timeout and a handler that explains it |
When Vaadin is the wrong choice
Vaadin earns its place in applications that look like software: forms, tables, workflows, dashboards, used by a known group of people, written by a Java team. It is a poor fit for:
- Public, content-heavy sites that need to rank in search. Server-rendered pages and static generation do this better.
- Highly custom, animation-driven or offline-first interfaces. You will fight the generic client.
- Teams with strong frontend skills and a mobile app to share an API with. A typed REST or GraphQL API serves both, see REST design for Java teams for how to do it well.
- Very large numbers of concurrent anonymous users. Per-session server memory is the cost.
A middle option for teams that want server-rendered pages with small interactive pieces is a template engine plus HTMX, compared in Vaadin against HTMX and Thymeleaf. For a bigger application that persists data, the next step is a CRUD application with JPA, and when a component you need does not exist, write your own.
A short checklist before you call it done
- Services own transactions and authorization; views call services.
- Every route has an access annotation, and sensitive services check roles too.
- Large grids use the lazy callback with a bounded page size.
- Long operations run off the UI thread and return through
ui.access. - Memory per session is measured under load.
- The built jar, with the production profile, is what CI tests and deploys.
- Version upgrades read the release notes: component APIs change between majors.
The entry point for everything else is the Vaadin documentation, and the data binding reference is binding data to forms.


