This reference card is tailored to developers with previous Vaadin experience. It is a quick reference on key concepts and everyday tasks that arise while using the framework. For a comprehensive reference or tutorials to learn Vaadin, see the links in the Useful links section below.
Useful links
Learn: https://vaadin.com/docsCreate new projects: https://start.vaadin.com
Edit a theme: https://demo.vaadin.com/lumo-editor
Search Vaadin Icons: https://vaadin.com/components/vaadin-icons/html-examples
Search UI components: https://vaadin.com/docs/latest/ds/components
Find Add-ons: https://vaadin.com/directory
Ask questions: https://stackoverflow.com/questions/tagged/vaadin or https://discord.gg/MYFq5RTbBn
Report issues: https://github.com/vaadin/platform/issues
Minimal application using Maven
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
<dependencies>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-core</artifactId>
<version>23.0.0</version>
</dependency>
</dependencies>
</project>
MainView.java:
import com.vaadin.flow.component.Text;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Route;
@Route("demo") // localhost:8080/demo
public class MainView extends VerticalLayout {
public MainView() {
add(new Text("It works!"));
}
}
UI Components
All Java UI components are instances of Component.
Input
CheckBox, ComboBox, DatePicker, Grid, TextField, TextArea, TimePicker, PasswordField, RadioButtonGroup, Upload, CustomField, EmailField, NumberField, RadioButton, Select, IntegerField, BigDecimalField, CheckBoxGroup, MultiSelectListBox, DateTimePicker.
Visualization and interaction
Accordion, Button, ContextMenu, Details, Dialog, Grid, Icon, Item, MenuBar, Notification, ProgressBar, Tabs, TreeGrid.
HTML
Div, Span, Section, Header, Footer, Article, H1, H2, H3, H4, H5, H6, Paragraph, Label, Anchor, OrderedList, ListItem, Image, DescriptionList, Emphasis, Hr, IFrame, Input, Main, NativeButton, Nav, Pre, Section, UnorderedList.
Layouts
FlexLayout, HorizontalLayout, Scroller, VerticalLayout, SplitLayout, AppLayout, FormLayout, Login.
Mixin interfaces
UI components implement mixin interfaces with default methods to build up the functionality of the component. For example, CheckBox
implements the HasSize, HasStyle, Focusable, ClickNotifier,
and HasValueAndElement
interfaces.
Interface |
Purpose |
Methods |
|
Handles blur events. |
|
|
Handles click events. |
|
|
Handles DOM Composition events (text input). |
|
|
Focus, blur, and set tab order (extends |
|
|
Handles focus events. |
|
|
Enables use of the autocapitalize attribute. |
|
|
Enables use of the autocomplete attribute. |
|
|
Enables use of the autocorrect attribute. |
|
|
Adds and removes child components (extends |
|
|
Enables data providers. |
|
|
Retrieves underlying element. |
|
|
Enables or disables components (extends |
|
|
Enables component ordering (extends |
|
|
Enables prefix and suffix slots for inserting components. |
|
|
Enables component sizing. |
|
|
Enables CSS styles and CSS class names. |
|
|
Enables text content. |
|
|
Enables theming. |
|
|
Enables input validation. |
|
|
Enables user-editable values. |
|
|
Extends |
See extended interfaces. |
|
Handles input events. |
|
|
Handles keyboard events. |
|
|
Handles events for asynchronous UI updates. |
|
|
Handles sort events. |
|
Sizing
VerticalLayout, HorizontalLayout, FlexLayout |
|
|
Sets the component size in units (px, pt, pc, cm, mm, in, em, or rem) or percentage (%) relative to the available area in the containing layout. null or -1 means an undefined size (see below). |
|
Sets both dimensions to 100% relative size. |
|
Sets the corresponding dimension to 100% relative size. |
|
Sets both dimensions as undefined, causing the component to shrink to its minimum size. |
|
Sets the minimum size of the component in units. |
|
Sets the maximum size of the component in units. |
|
Sets the flex grow property to 1 for the specified components. |
|
Specifies the proportion of the available space a component takes. |
VerticalLayout, HorizontalLayout |
|
|
Sets how the total width and height of a component is calculated. See the |
FlexLayout |
|
|
Sets how components shrink relative to the other components in the layout. |
|
Sets the initial main size of a component. |
Alignment
VerticalLayout, HorizontalLayout, FlexLayout |
|
|
Aligns the contained components. Default: |
|
Same as |
|
Sets how the extra space inside the layout is distributed among the components. Equivalent to the justify-content CSS property. |
VerticalLayout, HorizontalLayout |
|
|
Changes the default alignment of the contained components. |
|
Aligns the contained components in the "other" axis of the layout (for example, horizontally in a |
FlexLayout |
|
|
Sets how the "lines" within the layout are aligned when there is extra space. See the |
|
Sets the direction in which the components are layed out (as a column or a row) with the possibility to reverse the order. See the |
|
Sets how the contained components behave when they don't fit inside the layout. See the |
Alignment on the primary axis
Alignment on the secondary axis
AppLayout
|
Defines whether the navbar or the drawer display first. |
|
Shows or hides the drawer section. |
Navigation
TIP:
Register views at runtime in a ServiceInitListener implementation RouteConfiguration.forSessionScope().setRoute("view",View.class);
Parameters
@Route("")
public class GreetingView extends VerticalLayout
implements HasUrlParameter<> {
@Override
public void setParameter(BeforeEvent event,
parameter) {
String name = event.getLocation()
.getQueryParameters()
.getParameters()
.get("name")
.get(0);
add(new Span(parameter + ", " + name));
}
}
TIP:
Use @OptionalParameter
and@WildcardParameter
when needed.
Navigation lifecycle
Interface |
Description |
|
Allows delaying or canceling the navigation, or changing the navigation to a different destination. Reroute with the Reroute and update the browser URL with the |
|
Allows changing the navigation to a different destination. Reroute with the Reroute and update the browser URL with the |
|
Allows updating parts of the UI once the navigation has been completed. |
* Needs to be defined in a UI init listener if you want it to run before any views are created, for instance for general access control.
NOTE:
You cannot navigate from a constructor. Use BeforeEnterListener
and reroute accordingly.
Forms and data binding
Binder is a helper class to set values in Java beans from input fields and vice versa.
new Binder<>(Person.class); // property names supported
new Binder<>(); // property names not supported
Java Bean Validation
BeanValidationBinder<Person> binder = new BeanValidationBinder<>(Person.class);
if (binder.validate().isOk()) {
...
}
Requires Java Bean Validation in the classpath
Basic configuration
binder.bind(textField, Person::getName, Person::setName);
Or:
binder.bind(
textField,
person -> person.getName(),
(person, name) -> person.setName(name)
);
Binding
Two-way data binding. Sets the bean values in the input fields and sets values in the bean when the input fields values change:binder.setBean(person);
One-way data binding. Sets values from the bean to the input fields:binder.readBean(bean);
One-way data binding. Sets values from the input fields to the bean:binder.writeBean(bean);
Gets the bean:Person person = binder.getBean();
Advanced usage
binder.forField(ageTextField)
.asRequired("Is required")
.withNullRepresentation("")
.withConverter(new StringToIntegerConverter(
"Must be an integer"))
.withValidator(age -> age > 0,
"Must be a positive integer")
.withStatusLabel(ageStatus)
.bind(p -> p.getAge(), (p, age) -> p.setAge(age));
try {
binder.writeBean(person);
...
} catch (ValidationException e) {
...
}
NOTE:
If you used setBean
earlier, useif(movieBinder.validate().isOk()){...}
TIP:
Use the writeBeanAsDraft(BEAN)
and writeBeanIfValid(BEAN)
methods when needed.
Bind by field name
TIP:
Use @Id
when possible to improve maintainability.
Sessions, Views, and UIs
TIP:
Reuse view instances using @PreserveOnRefresh
. A new UI instance is created after a browser refresh.
Using the Vaadin Session
|
|
|
Stores an object by name. |
|
Stores an object by type. |
|
Gets a stored object by name. |
|
Gets a stored object by type. |
|
Flags the session for discarding (doesn't destroy the HTTP session). |
TIP:
Invalidate the HTTP session with VaadinSession.getCurrent().getSession().invalidate();
Application lifecycle
Servlet customization
public class CustomServlet extends VaadinServlet {
@Override
protected void servletInitialized() throws ServletException {
super.servletInitialized();
...your logic here...
}
}
Register the servlet using @WebServlet
or in the web.xml
file.
Once per VaadinService instance
public class AppServiceInitListener
implements VaadinServiceInitListener {
@Override
public void serviceInit(ServiceInitEvent event) {
event.addBootstrapListener(response -> {
...change the bootstrap page...
});
event.addDependencyFilter((dependencies, filterContext) -> {
...add/remove/change client-side dependencies...
return dependencies;
});
event.addRequestHandler((session, request, response) -> {
...change how responses are handled...
return false;
});
}
}
In a Spring Boot project, it is sufficient to register this listener by adding the @Component
annotation to the class.
In plain Java projects, the listener should be registered as a provider by adding the following file:
With the following content:com.company.AppServiceInitListener
Session destroy listeners
public class ApplicationServiceInitListener
implements VaadinServiceInitListener {
@Override
public void serviceInit(ServiceInitEvent initEvent) {
initEvent.getSource().addSessionDestroyListener(
sessionEvent -> {
... your logic here ...
});
}
}
UI component attach/detach
Use these methods to free resources and clean up:
public class CustomComponentOrView extends VerticalLayout {
@Override
protected void onAttach(AttachEvent attachEvent) {
...custom logic when the component is attached to the UI ...
}
@Override
protected void onDetach(DetachEvent detachEvent) {
...custom logic when the component is detached from the UI...
}
}
TIP:
Use addAttachListener(ComponentEventListener<AttachEvent>)
and addDetachListener(ComponentEventListener<DetachEvent>)
to clean up conditionally.
Heartbeat
The objective of the heartbeat mechanism is to remove UI instances that are no longer active in the same session.
The client-side sends keep-alive heartbeat requests at a configurable rate. A UI expires if three consecutive heartbeats are missed.
NOTE:
The HTTP session doesn't expire if there is a browser window open. This is a side effect of the heartbeats. Use the closeIdleSessions
configuration parameter to override this behavior.
Static content
Templates, CSS, Javascript, images:
WAR |
src/main/webapp/frontend/ |
JAR |
src/main/resources/META-INF/resources/frontend/ |
Favicon:
WAR |
src/main/webapp/icons/icon.png |
JAR |
src/main/resources/META-INF/resources/icons/icon.png |
NOTE:
These resources are not bundled.
TIP:
Use the PageConfigurator
interface to customize the name and location of the favicon.
Styling
Dark Theme
@Theme(value = Lumo.class, variant = Lumo.DARK)
public class MainView extends ... { }
Custom CSS
CSS (PROJECT_ROOT/frontend/css-file.css):
.css-class-name {
... custom css rules ...
}
Java (View.java):
...
@CssImport("./styles/css-file.css")
public class MainView extends ... {
public MainView() {
...
Button button = new Button();
button.addClassName("css-class-name");
}
}
Shadow DOM
Vaadin components are web components in the client side. The client-side implementation is encapsulated inside the Shadow DOM.
Java:
@CssImport(value = "./styles/styles.css", )
public class MainView extends VerticalLayout { ... }
NOTE:
Only works for web components that implement vaadin-themable-mixin.
CSS (styles.css):
[part="label"] {
… custom CSS ...
}
TIP:
Use the browser inspector to see the available parts of a web component
Responsive design
Components such as AppLayout and FormLayout include responsive features. Use CSS media queries to fully customize layouts.
@media only screen and (min-width: 1024px) {
html {
… custom CSS ...
}
}
Production builds
Performed with the vaadin-maven-plugin
and the prepare-frontend
and build-frontend
goals. Projects created with the Maven archetype or on the Vaadin web site can activate a production build with mvn package -Pproduction
.
NOTE:
A production build is necessary to deploy to external servers.
Maven profile (all Vaadin starters include this profile):
<profile>
<id>production</id>
<properties>
<vaadin.productionMode>true</vaadin.productionMode>
</properties>
<dependencies>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>flow-server-production-mode</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>build-frontend</goal>
</goals>
<phase>compile</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
A production build reduces the bundle size in several ways:
- Debugging information (main source maps) not included.
- The JS implementation is included only for components that are used (Java classes are analyzed).
- The script content is minified.
- The client-side bundle is gzipped.
Configuration properties
|
Switches application to production mode. |
|
Whether request timing info is available. This can be used for performance testing. |
|
Enables or disables cross-site request-forgery protection. |
|
The interval in seconds between UI heartbeat requests, or a negative number if heartbeats are disabled. |
|
Whether a session should be closed when all its open UIs have been idle for longer than its configured maximum inactivity time. |
|
Options: disabled or manual. |
|
URL used for push requests. |
|
Enables or disables id checking. The sync id is used to gracefully handle situations when the client sends a message to a connector that has recently been removed on the server. |
|
Enables or disables sending of URLs as GET and POST parameters in requests with content type application /x-www-form-urlencoded. |
|
Long poll push strategy timeout in milliseconds |
|
Maximum time in milliseconds that the client will wait for the predecessors of a received out-of-order message. |
|
Includes polyfills for browsers that don't support ES6. |
|
Location of the web component's files for browsers that don't support ES6. |
|
Location of the web component's files for browsers that support ES6. |
|
Enables or disables WebJars. |
|
Whether to use bundled fragments. |
|
I18NProvider implementation. |
|
Whether the framework should register automatic servlets for the application. |
|
Enables Vaadin 13 compatibility mode. |
|
Enables or disables bytecode scanning in dev mode. If enabled, entry points are scanned for reachable frontend resources. If disabled, all classes on the classpath are scanned. |
|
Whether to use pnpm instead of npm for resolving and downloading of frontend dependencies. |