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.

 

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.

Frame 14

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

BlurNotifier

Handles blur events.

addBlurListener

ClickNotifier

Handles click events.

addClickListener

CompositionNotifier

Handles DOM Composition events (text input).

addCompositionStartListener

addCompositionUpdateListener

addCompositionEndListener

Focusable

Focus, blur, and set tab order (extends HasElement, BlurNotifier, FocusNotifier, and HasEnabled).

setTabIndex

getTabIndex

focus

blur

FocusNotifier

Handles focus events.

addFocusListener

HasAutocapitalize

Enables use of the autocapitalize attribute.

setAutocapitalize

getAutocapitalize

HasAutocomplete

Enables use of the autocomplete attribute.

setAutocomplete

getAutocomplete

HasAutocorrect

Enables use of the autocorrect attribute.

setAutocorrect

isAutocorrect

HasComponents

Adds and removes child components (extends HasElements and HasEnabled).

add

remove

removeAll

HasDataProvider

Enables data providers.

setDataProvider

setItems

HasElement

Retrieves underlying element.

getElement

HasEnabled

Enables or disables components (extends HasElement).

setEnabled

isEnabled

HasOrderedComponents

Enables component ordering (extends HasComponents).

replace

indexOf

getComponentCount

getComponentAt

HasPrefixAndSuffix

Enables prefix and suffix slots for inserting components.

setPrefixComponent

getPrefixComponent

setSufixComponent

getSufixComponent

HasSize

Enables component sizing.

setWidth

getWidth

setHeight

getHeight

setSizeFull

setSizeUndefined

HasStyle

Enables CSS styles and CSS class names.

addClassName

removeClassName

setClassName

getClassName

hasClassName

addClassNames

removeClassNames

getStyle

HasText

Enables text content.

setText

getText

HasTheme

Enables theming.

addThemeName

removeThemeName

setThemeName

getThemeName

getThemeNames

setThemeName

hasThemeName

addThemeNames

removeThemeNames

HasValidation

Enables input validation.

setErrorMessage

getErrorMessage

setInvalid

isInvalid

HasValue

Enables user-editable values.

setValue

getValue

addValueChangeListener

getEmptyValue

getOptionalValue

isEmpty

clear

setReadOnly

isReadOnly

setRequiredIndicatorVisible

isRequiredIndicatorVisible

HasValueAndElement

Extends HasValue, HasElement, and HasEnabled.

See extended interfaces.

InputNotifier

Handles input events.

addInputListener

KeyNotifier

Handles keyboard events.

addKeyDownListener

addKeyPressListener

addKeyUpListener

PollNotifier

Handles events for asynchronous UI updates.

addPollListener

SortNotifier

Handles sort events.

addSortListener

 

Sizing

VerticalLayout, HorizontalLayout, FlexLayout

setWidth(String)

setHeight(String)

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).

setSizeFull()

Sets both dimensions to 100% relative size.

setHeightFull()

setWidthFull()

Sets the corresponding dimension to 100% relative size.

setSizeUndefined()

Sets both dimensions as undefined, causing the component to shrink to its minimum size.

setMinWidth(String)

setMinHeight(String)

Sets the minimum size of the component in units.

setMaxWidth(String)

setMaxHeight(String)

Sets the maximum size of the component in units.

expand(Component...)

Sets the flex grow property to 1 for the specified components.

setFlexGrow(double)

Specifies the proportion of the available space a component takes.

VerticalLayout, HorizontalLayout

setBoxSizing(BoxSizing)

Sets how the total width and height of a component is calculated. See the BoxSizing enum values.

FlexLayout

setFlexShrink(double, HasElement...)

Sets how components shrink relative to the other components in the layout.

setFlexBasis(String, HasElement...)

Sets the initial main size of a component.

Alignment

VerticalLayout, HorizontalLayout, FlexLayout

setAlignItems(Alignment)

Aligns the contained components. Default: STRETCH

setAlignSelf(Alignment, HasElement...)

Same as setHorizontalComponentAlignment or setVerticalComponentAlignment.

setJustifyContentMode(JustifyContentMode)

Sets how the extra space inside the layout is distributed among the components. Equivalent to the justify-content CSS property.

VerticalLayout, HorizontalLayout

setDefaultHorizontalComponentAlignment(Alignment)

Changes the default alignment of the contained components.

setHorizontalComponentAlignment(Alignment, Component...)
setVerticalComponentAlignment(Alignment, Component...)

Aligns the contained components in the "other" axis of the layout (for example, horizontally in a VerticalLayout)

FlexLayout

setAlignContent(ContentAlignment)

Sets how the "lines" within the layout are aligned when there is extra space. See the ContentAlignment enum values.

setFlexDirection(FlexDirection)

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 FlexDirection enum values.

setFlexWrap(FlexWrap)

Sets how the contained components behave when they don't fit inside the layout. See the FlexWrap enum values.

 

Frame 8

Alignment on the primary axis

Frame 9

Alignment on the secondary axis

Frame 10

AppLayout

Frame 11

setPrimarySection(Section)

Defines whether the navbar or the drawer display first.

setDrawerOpened(boolean)

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

BeforeLeaveObserver

BeforeLeaveListener

Allows delaying or canceling the navigation, or changing the navigation to a different destination.


Reroute with the BeforeLeaveEvent::reroute() methods.


Reroute and update the browser URL with the BeforeLeaveEvent::forward() methods.

BeforeEnterObserver*

BeforeEnterListener

Allows changing the navigation to a different destination.


Reroute with the BeforeEnterEvent::reroute() methods.


Reroute and update the browser URL with the BeforeEnterEvent::forward() methods.

AfterNavigationObserver

AfterNavigationListener

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, use
if(movieBinder.validate().isOk()){...} 

TIP:

Use the writeBeanAsDraft(BEAN) and writeBeanIfValid(BEAN) methods when needed.

Bind by field name

Frame 12

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

Frame 13

VaadinSession.getCurrent()

setAttribute(String, Object)

Stores an object by name.

setAttribute(Class<T>, T)

Stores an object by type.

getAttribute(String)

Gets a stored object by name.

getAttribute(Class<T>)

Gets a stored object by type.

close()

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

productionMode

Switches application to production mode.

requestTiming

Whether request timing info is available. This can be used for performance testing.

disable-xsrf-protection

Enables or disables cross-site request-forgery protection.

heartbeatInterval

The interval in seconds between UI heartbeat requests, or a negative number if heartbeats are disabled.

closeIdleSessions

Whether a session should be closed when all its open UIs have been idle for longer than its configured maximum inactivity time.

pushMode

Options: disabled or manual.

pushURL

URL used for push requests.

syncIdCheck

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.

sendUrlsAsParameters

Enables or disables sending of URLs as GET and POST parameters in requests with content type application /x-www-form-urlencoded.

pushLongPollingSuspendTimeout

Long poll push strategy timeout in milliseconds

maxMessageSuspendTimeout

Maximum time in milliseconds that the client will wait for the predecessors of a received out-of-order message.

load.es5.adapters

Includes polyfills for browsers that don't support ES6.

frontend.url.es5

Location of the web component's files for browsers that don't support ES6.

frontend.url.es6

Location of the web component's files for browsers that support ES6.

disable.webjars

Enables or disables WebJars.

original.frontend.resources

Whether to use bundled fragments.

i18n.provider

I18NProvider implementation.

disable.automatic.servlet.registration

Whether the framework should register automatic servlets for the application.

compatibilityMode

Enables Vaadin 13 compatibility mode.

devmode.optimizeBundle

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.

pnpm.enable

Whether to use pnpm instead of npm for resolving and downloading of frontend dependencies.