Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}
Refcard #085

Getting Started With Vaadin Framework 8

Modern Web Apps in Java

Written by

Matti Tahvonen Vaadin Expert, Vaadin
Marko Grönroos Technical Writer, IT Mill

Vaadin gives you the opportunity to develop modern web applications that provide a great user experience and look great. Using a built-in selection of components, themes, data binding, and more, Vaadin is the ideal in web application development frameworks.

Free PDF
Brought to you by Vaadin
Section 1

About Vaadin Framework

Vaadin Framework is a productive and easy-to-use UI library for developing web applications in Java or your JVM language of choice. Vaadin’s strong abstraction of web technologies gives you a component-based approach to build your apps, almost like you’re building traditional desktop apps, but through state-of-the-art web technologies. You use an object-oriented approach to compose your UI from smaller UI components and layouts, and hook your logic to the UI with event listeners.

In addition to providing high-level UI components, which saves you from time-consuming HTML, CSS, and JavaScript programming, Vaadin also abstracts away the communication between the server and the browser. This makes both the UI and backend development easier (no need to expose REST services) and increases security.

Vaadin Framework is open source and licensed under the liberal Apache 2 license.

Image title


Figure 1: Vaadin Client-Server Architecture

For extending the framework, there are numerous add-ons built by Vaadin and the community. The Directory service currently lists nearly 700 add-ons for Vaadin Framework.

Section 2

Bootstrapping a Project

You can create a Vaadin application project easily from Maven archetypes. To create a simple app stub, use the following command (or use the same groupId and archetypeId in your IDE):

mvn archetype:generate -DarchetypeGroupId=com.vaadin -DarchetypeArtifactId=vaadin-archetype-application -DarchetypeVersion=LATEST

start.spring.io also provides an option to include Vaadin dependencies to your Spring project. The most commonly used IDEs (IntelliJ, Eclipse, and Netbeans) also have built in support or plugins that can help to create Vaadin applications.

The UI Class: The Entry Point to Your Application

The UI class (extends the com.vaadin.UI) is the entry point to your application. The framework creates an instance when the user opens the page in the browser and calls the init method init().

@Title(“My Vaadin UI”)
  public class HelloWorld extends com.vaadin.UI {    
    @Override
    protected void init(VaadinRequest request) {
    // Create the content root layout for the UI
    VerticalLayout content = new VerticalLayout();
    setContent(content);
    // Display the greeting
    content.addComponent(new Label(“Hello World!”));
  }
}

Normally, you need to:

  • Extend the UI class.

  • Build an initial UI from components.

  • Define event listeners to implement the UI logic.

Optionally, you can also:

  • Set a custom theme for the UI.

  • Bind components to data.

  • Bind components to resources.

Image title

Figure 2: Class Diagram

Tip: You can get a reference to the UI object associated with the currently processed request from anywhere in the application logic with UI.getCurrent(). You can also access the current VaadinSession, VaadinService, and VaadinServlet objects in the same way.

Deployment

To expose UI classes for end users, you’ll need a VaadinServlet deployed to a servlet container. The VaadinServlet handles server requests and manages user sessions and UIs. If you use Vaadin Spring or Vaadin CDI (available in the Vaadin Directory), the servlet is configured automatically, and you only need to expose your UI class using @SpringUI or @CDIUI(“”) annotation. In a basic servlet container project, like the one that is generated by vaadin-archetype-application, the servlet can be declared as such:

@WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
@VaadinServletCon guration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {

}

Most of the time you don’t need to work at the servlet level at all, but you can add customization to the servlet if you want. In Spring and CDI projects, you can just expose a customized version of SpringVaadinServlet or VaadinCDIServlet and the automatic default version is then ignored.

Vaadin UIs can also be deployed as portlets in a portal. Refer to vaadin.com/docs for Portlet deployment.

Events Listeners

In the event-driven model, user interactions with user interface components trigger server-side events, which you can handle with event listeners.

In the following example, we handle click events for a button with an anonymous class:

Button button = new Button(“Click Me”); 
button.addClickListener(event-> {
  Notification.show(“Thank You!”);
});
layout.addComponent(button);

Different components provide different listeners. For example, value changes in a field component can be handled with a ValueChangeListener, and TabSheet allows you to listen to tab changes using SelectedTabChangeListener. Many field components allow to track focus using FocusListener.

In addition to the event-driven model, UI changes can be made from other places than UI initiated threads. Changes are reflected automatically if you have enabled server push (using vaadin-push module and @Push annotation to UI class) or use polling configured to the UI class. The push mode primarily uses WebSockets for communication and falls back to long polling if it’s not supported.

public void notifyUI(YourAppUI activeUI, String msg) {
  // ensure proper synchronization using the UI.access method
  // when called from a non-UI initiated event
  activeUI.access(() -> {
    activeUI.showMessageInUI(msg); // method in your UI class
  });
}
Section 3

Components

Vaadin components include field, layout, and other components. The component classes and their inheritance hierarchy is illustrated in Figure 2.

Component Properties

Common component properties are defined in the Component interface and the AbstractComponent base class for all components.

Property

Description

Caption

A label usually shown above, left of, or inside a component, depending on the component and the containing layout.

Description

A longer description that is usually displayed as a tooltip when the mouse hovers over the component.

Enabled

If false, the component is shown as grayed out and the user cannot interact with it. (Default: true.)

Icon

An icon for the component, usually shown left of the caption, specified as a resource reference.

Locale

The current country and/or language for the component. Meaning and use is application-specific for most components. (Default: UI locale.)

Visible

Whether the component is visible or not. (Default: true.)

Field Properties

Field implementations often extend from AbstractField<T> and contain the following commonly used properties.

Property

Description

value

The actual value of the field. The type depends on the field and possible configuration. Value changes can be monitored using ValueChangeListener, but often values are bound automatically using com.vaadin.data.Binder.

requiredIndicatorVisible

A Boolean controlling whether the component should be marked as required in the UI (most often using red * character).

readOnly

If true, the user cannot change the value. (Default: false.)

tabIndex

The tab index property is used to specify the order in which the fields are focused when the user presses the Tab key.

Sizing

The size of components can be set in fixed or relative units by either dimension (width or height), or be undefined to shrink to fit the content.

Method

Description

setWidth()

setHeight()

Set the component size in either fixed units (px,pt, pc, cm, mm, in, em, or rem) or as a relative percentage (%) of the available area provided by the containing layout. The null value or -1 means undefined size (see below), causing the component to shrink to fit the content.

setSizeFull()

Sets both dimensions to 100% relative size.

setSizeUndefined()

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

Figure 4 shows the default sizing of components.

Notice that a layout with an undefined size must not contain a component with a relative (percentual) size. For more tips on how to use relative sizes, refer to the Layout section.


Resources

Icons, embedded images, hyperlinks, and downloadable files are referenced as resources.

Button button = new Button(“Button with an icon”);
button.setIcon(new ThemeResource(“img/myimage.png”));

External and theme resources are usually static resources. Connector resources are served by the Vaadin servlet.

Image title

Figure 3: Resource Classes and Interfaces

Class Name

Description

ExternalResource

Any URL.

ThemeResource

A static resource served by the application server from the current theme. The path is relative to the theme folder.

FileResource

Loaded from the file system.

ClassResource

Loaded from the class path.

StreamResource

Provided dynamically by the application.

FontIcon

Font icon sets, such as VaadinIcons, contain a selection of special resources that can be used as icons.

Section 4

Layout Components

The layout of a UI is built hierarchically from layout components, or more generally component containers, with the actual interaction components as the leaf nodes of the component tree.

You start by creating a root layout and setting it as the UI content with setContent(). Then you add the other components to that with addComponent(). Single-component containers, most notably Panel and Window, only hold a single content component, just as UI, which you must set with setContent().

The sizing of layout components is crucial. Their default sizes are marked in Figure 4, and can be changed with the sizing methods described earlier. Notice that if all the components in a layout have relative size in a particular direction, the layout may not have undefined size in that direction!

Tip: Besides building your layouts in Java, you can also layout your view in declarative HTML format or visually by using Vaadin Designer inside Eclipse or IntelliJ.

Margins

Certain layout components support setting margins programmatically. Setting setMargin(true) enables all margins for a layout, and with a MarginInfo parameter you can enable each margin individually. The margin sizes can be adjusted with the padding property (as top, bottom, left, and right padding) in a CSS rule with a corresponding v-top-margin, v-bottom- margin, v-left-margin, or v-right-margin selector. For example, if you have added a custom mymargins style to the layout:

.mymargins.v-margin-left {padding-left: 10px;}
.mymargins.v-margin-right {padding-right: 20px;}
.mymargins.v-margin-top {padding-top: 30px;}
.mymargins.v-margin-bottom {padding-bottom: 40px;}

Spacing

Certain layout components also support the setSpacing(true) method that controls spacing between the layout slots. Spacing can be adjusted with CSS as the width or height of the elements with the v-spacing style. For example, for a vertical layout:

.v-vertical > .v-spacing {height: 50px;}

For a GridLayout, you need to set the spacing as left/top padding for a .v-gridlayout-spacing-on element:

.v-gridlayout-spacing-on { 
  padding-left: 100px;
  padding-top: 50px; 
}

Alignment

When an area provided by the layout component is larger than a contained component, the component can be aligned within the cell with the setComponentAlignment() method as in the example below:

VerticalLayout layout = new VerticalLayout();
Button button = new Button(“My Button”);
layout.addComponent(button);
layout.setComponentAlignment(button, Alignment.MIDDLE_CENTER);

Expanding Components to Available Space

The ordered layouts and GridLayout support expand ratios allow some components to take the remaining space left over from other components. The ratio is a float value and components have 0.0f default expand ratio. The expand ratio must be set after the component is added to the layout.

VerticalLayout layout = new VerticalLayout();
layout.setSizeFull();
layout.addComponent(new Label(“Title”)); // Doesn’t expand
TextArea area = new TextArea(“Editor”); 
area.setSizeFull();
layout.addComponent(area); 
layout.setExpandRatio(area, 1.0f)

VerticalLayout and HorizontalLayout also contain a helper method called addComponentsAndExpand(Component…) that adds a component and adjusts expand ratios and component sizes that suit most common use cases. The above can be flattened to:

VerticalLayout layout = new VerticalLayout();
layout.addComponent(new Label("Title")); // Doesn’t expand
TextArea area = new TextArea("Editor"); 
layout.addComponentsAndExpand(area);

The Grid component also supports expand ratios for columns.

Custom Layout

The CustomLayout component allows the use of an HTML template that contains location tags for components, such as <div location=”hello”/>. The components are inserted in the location elements with the addComponent() method as shown below:

CustomLayout layout = new CustomLayout(
        getClass().getResourceAsStream("mylayout.html"));
layout.addComponent(new Button("Hello"), "hello");


The layout content is given as an InputStream or it can also be a named resource file in your theme directory.

Section 5

Add-on Components

Your application might require less frequently needed features or UI components, which are not included in the core distribution. Hundreds of Vaadin add-on components are available in the Vaadin Directory, both free and commercial. To use a component, just copy the dependency information for Maven or download the jar files from Directory into your project.

Many of the add-ons contain client side extensions. These add-ons require you have a widgetset that combines both built in and custom client side extensions into one compact client side engine. If you created your add-on with vaadin-archetype-application, your application is ready for add-on usage out of the box, but remember to execute "mvn clean install" (or the same via your IDE) to ensure the client side engine is rebuilt.

If your project doesn't have vaadin-maven-plugin (e.g. a start.spring.io project or simplified example app), add the following build plugin to your project's pom.xml file:

<plugin>
    <groupId>com.vaadin</groupId>
    <artifactId>vaadin-maven-plugin</artifactId>
    <version>${version.vaadin}</version>
    <executions>
        <execution>
            <goals>
                <!-- Needed for theme: -->
                <goal>update-widgetset</goal>
                <goal>compile</goal>
                <!-- Needed for theme: -->
                <goal>update-theme</goal>
                <goal>compile-theme</goal>
            </goals>
        </execution>
    </executions>
</plugin>
Section 6

Themes

Vaadin allows customization of the appearance of the user interface with themes. Themes can include Sass or CSS style sheets, custom layout HTML templates, and graphics.

Basic Theme Structure

Custom themes are placed under the /VAADIN/themes/ folder of the web application (src/main/webapp in Maven projects). This location is fixed and the VAADIN folder specifies that these are static resources specific to your Vaadin application. The structure is illustrated in Figure 5.

Each theme has its own folder with the name of the theme. A theme folder must contain a styles.scss (for Sass) or a styles.css (for plain CSS) style sheet. Custom layouts must be placed in the layout’s sub-folder, but other contents may be named freely.

Custom themes need to inherit a base theme. The suggested base theme is Valo, which is easily customizable using Sass variables. Such a theme is created for you automatically if you bootstrap your project is built on top of the vaadin-archetype-application archetype.

Sass Themes

Sass (Syntactically Awesome StyleSheets) is a stylesheet language based on CSS3, with some additional features such as variables, nesting, mixins, and selector inheritance. Sass themes need to be compiled to CSS. Vaadin includes a Sass compiler that compiles stylesheets during the build process. You can also use on-the-fly compilation during development, by disabling the compilation from the build script.

To enable multiple themes on the same page, all the style rules in a theme should be prefixed with a selector that matches the name of the theme. It is defined with a nested rule in Sass. Sass themes are usually organized in two files: a styles.scss and a theme-specific file such as mytheme.scss.

With this organization, the styles.scss would be as follows:

@import "mytheme.scss";
@import "addons.scss";

// This file prefixes all rules with the theme name to avoid causing conflicts with other themes.
// The actual styles should be defined in mytheme.scss

.mytheme {
  @include addons;
  @include mytheme;
}

The mytheme.scss, which contains the actual theme rules, would define the theme as a Sass mix-in as follows:

@import "../valo/valo.scss";

@mixin mytheme {
  @include valo;

  // Insert your own theme rules here
  .mycomponent { color: red; }  
}

Image title

Figure 4: Theme Contents

Applying a Theme

Every component has a default CSS class based on the component type, and you can add custom CSS classes for UI components with addStyleName(), as shown below.

You set the theme for a UI with the @Theme annotation.

@Theme("mytheme")
public class MyUI extends UI {

    @Override
    protected void init(VaadinRequest vaadinRequest) {
//...
    Label label = new Label("This is my themed component");
    label.addStyleName("mycomponent");
    layout.addComponent(label);
    }
Section 7

Data Binding

Vaadin allows binding your Java domain classes directly to components. This way, you avoid writing a lot of boilerplate code.

Listing Data in Grid

Grid, the component that shows your data in tabular format, often plays a central part in a business application. The easiest way to use Grid is to pass the data as a list, stream or an array. In the following code example, Person is your domain object (Java Bean):

Grid<Person> grid = new Grid<>(Person.class);
grid.setItems(listOfPersons);
// define columns and the order as bean properties (default: show all)
grid.setColumns("firstName", "lastName", "email");

Alternatively, you can define columns programmatically. In this case, you don’t need to pass the domain type as a constructor parameter:

Grid<Person> grid = new Grid<>();
grid.setItems(listOfPersons);
grid.addColumn(Person::getFirstName).setCaption("First name");
// ...

The addColumn method returns a Column object that can be used to further configure the column and the data representation. In the above example, we only configure the caption of the column. With bean based listing your can get a reference to the Column with getColumn(“propertyName”).

Lazy Loading Data in Grid

The setItems method stores the given data in your server memory for rapid access. If your data grid contains a lot of data and you wish to save some server memory, you can also do a lazy binding with your backend using setDataProvider method:

grid.setDataProvider(
  (sortOrders, offset, limit) ->
    service.findAll(offset, limit).stream(),
    () -> service.count()
);

The example above uses the easiest solution, in which you only provide two lambda expressions: the first to provide the given range of items and the second one that provides the total number of items available. Alternatively, you can provide a custom implementation of the DataProvider interface.

Selection Components

Selection components (ComboBox, RadioButtonGroup, ListSelect...) let your users pick one or several selections from a set of given items. Grid is also a selection component. You can use it as a single or multi-selection component using asSingleSelect() or asMultiSelect() method.

To set the available items, you use the same setItems or setDataProvider methods, as with Grid. Most select components by default render the selections using item’s toString method. Selecting a String from a list of strings could be accomplished as follows:

ComboBox<String> comboBox = new ComboBox<>();
comboBox.setItems(“Foo”,”Bar”,”Car”);
comboBox.addValueChangeListener(e -> Notification.show(e.getValue()));

If toString presentation doesn’t fit to your use case, you can in most select components customize the caption as follows:

ComboBox<Person> cb = new ComboBox<>();
cb.setItemCaptionGenerator(p -> p.getFirstName() + " " + p.getLastName());

A similar concept is available for icons.

Binder for Handy Forms

Binder is a helper class that allows you to bind a single Java object’s properties to be displayed in multiple Vaadin components. The most typical use case is a form. Binder also supports two-way binding, so that values input by the end user automatically get written back to your domain model.

Binder will also help you to do value conversion and validation for the data. The following binds firstName(String) and age (Integer) to two text fields.

Binder<Person> b = new Binder<>();
b.forField(firstNameField)
// additional configuration
.asRequired("First name must be defined")
.bind(Person::getFirstName, Person::setFirstName);
b.forField(ageField)
.withConverter(new StringToIntegerConverter("Must be valid integer!"))
.withValidator(integer -> integer > 0, "Age must be positive")
.bind(p -> p.getAge(), (p, i) -> p.setAge(i));
b.setBean(person);

Alternatively, you can make an automatic binding to your UI classes member fields. The binding is made based on naming convention, but it can be overridden with @PropertyId annotation.

private TextField age = new TextField();
private TextField firstName = new TextField();

private void bindFields(Person person) {
Binder<Person> b = new Binder<>(Person.class);
// additional configuration supported also in name based binding
b.forMemberField(age)
.withConverter(new StringToIntegerConverter("Must be integer"));
// this binds all found fields
b.bindInstanceFields(this);
b.setBean(person);
}
Section 8

Widget Integration

The easiest way to create new components is composition with the CustomComponent or by extending from some layout component. If that is not enough, you can create an entirely new component by creating a client-side widget (in GWT or JavaScript), a server-side counterpart, and binding the two together with a connector, using a shared state and RPC calls.

Image title

Figure 5: Integrating a Client-Side widget with a Server-Side API

Shared state is used for communicating component state from the server-side component to the client-side connector, which should apply them to the widget. The shared state object is serialized by the framework.

You can make RPC calls both from the client-side to the server-side, typically to communicate user interaction events, and vice versa. To do so, you need to implement an RPC interface.

Creating a Widget Project

You can create widgets directly to your application project, but a much better habit is to create a separate add-on project for your custom widgets and then add dependency to it from your application projects. Then you can build better tests and are prepared for reuse in your other Vaadin projects or even sharing your add-ons with others via the Directory service.

For widgets, there is a specially tailored project template, vaadin-archetype-widget. Create a project using that archetype and follow its instructions in its README file. The archetype also creates stubs for required classes.

Publications

  • Featured
  • Latest
  • Popular
Design Patterns
Learn design patterns quickly with Jason McDonald's outstanding tutorial on the original 23 Gang of Four design patterns, including class diagrams, explanations, usage info, and real world examples.
214.6k 640.9k
Core Java
Gives you an overview of key aspects of the Java language and references on the core library, commonly used tools, and new Java 8 features.
135.6k 377.6k
Getting Started with Git
This updated Refcard explains why so many developers are migrating to this exciting platform. Learn about creating a new Git repository, cloning existing projects, the remote workflow, and more to pave the way for limitless content version control.
133.6k 305.3k
Getting Started with Ajax
Introduces Ajax, a group interrelated techniques used in client-side web development for creating asynchronous web applications.
103k 217.3k
Foundations of RESTful Architecture
The Representational State Transfer (REST) architectural style is a worldview that elevates information into a first-class element of architectures. REST allows us to achieve the architectural properties of performance, scalability, generality, simplicity, modifiability, and extensibility. This newly updated Refcard explains main HTTP verbs, describes response codes, and lists libraries and frameworks. It also gives additional resources to further explore each topic.
107.6k 187.7k
Spring Configuration
Catalogs the XML elements available as of Spring 2.5 and highlights those most commonly used: a handy resource for Spring context configuration.
105.6k 272.6k
Scrum
Scrum is a framework that allows people to productively and creatively deliver products of the highest possible value. With over 70% of Agile teams using Scrum or Scrum hybrid, learn more about its benefits in managing complex product development. This newly updated Refcard explores the details of Scrum, including theory, values, roles, and events. It also includes a sample of a popular approach to deliver Integrated Increments in a scaled environment.
97.9k 262.9k
Core CSS: Part I
Covers Core principles of CSS that will expand and strengthen your professional ability to work with CSS. Part one of three.
92k 203k
jQuery Selectors
Introduces jQuery Selectors, which allow you to select and manipulate HTML elements as a group or as a single element in jQuery.
94.6k 362.6k
Core Java Concurrency
Helps Java developers working with multi-threaded programs understand the core concurrency concepts and how to apply them.
92.9k 205.3k
Getting Started with Eclipse
Eclipse IDE is a cross-platform, multi-purpose, open-source Integrated Development Environment. It is widely used to develop projects in Java, JavaScript, PHP, C++, Scala, and many others. This newly updated Refcard breaks down installing, setting up, and getting started with Eclipse. It also covers productivity tips, creating new projects and files, accessing Source Control Managers, and debugging configurations.
82.3k 229.9k
Core CSS: Part II
Covers Core principles of CSS that will expand and strengthen your professional ability to work with CSS. Part two of three.
75k 144.3k
{{ card.title }}
{{card.downloads | formatCount }} {{card.views | formatCount }}

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}