Book Image

Data-Centric Applications with Vaadin 8

By : Alejandro Duarte
Book Image

Data-Centric Applications with Vaadin 8

By: Alejandro Duarte

Overview of this book

Vaadin is an open-source Java framework used to build modern user interfaces. Vaadin 8 simplifies application development and improves user experience. The book begins with an overview of the architecture of Vaadin applications and the way you can organize your code in modules.Then it moves to the more advanced topics about advanced topics such as internationalization, authentication, authorization, and database connectivity. The book also teaches you how to implement CRUD views, how to generate printable reports, and how to manage data with lazy loading. By the end of this book you will be able to architect, implement, and deploy stunning Vaadin applications, and have the knowledge to master web development with Vaadin.
Table of Contents (11 chapters)

Understanding the architecture of a Vaadin application

What's the best way of starting a new Vaadin project? It’s hard to say. It depends on your previous experience, current development environment setup, and your own preferences. One of the most popular ways of creating a new Vaadin project is by using one of the official Maven archetypes. You have probably used the vaadin-archetype-application Maven archetype, which is good to quickly get started with Vaadin. Maybe you have used the vaadin-archetype-widgetset archetype to create a Vaadin add-on, or maybe you have used the vaadin-archetype-application-multimodule or vaadin-archetype-application-example archetypes to bootstrap some of your applications. IDEs such as Eclipse provide tools to create a Vaadin project without even thinking about Maven archetypes.

All of those archetypes and tools are good in the sense that they get you started quickly and show some good practices. However, when you create a project from scratch, you get a better understanding of the whole architecture of the application. Of course, you can use the archetypes if you already feel comfortable enough with every part of the generated pom.xml file. However, building the project from scratch is a good way of truly understanding and controlling the configuration of your Vaadin application.

Creating a new project from scratch

Usually, you would use the vaadin-archetype-application or vaadin-archetype-application-multimodule Maven archetypes to create a new Vaadin application. There's nothing wrong with using these if the generated code suits your needs. However, these archetypes generate more code than you need, partially because they try to show you how to get started with Vaadin and partially because they are general-purpose starters which are well-suited for most projects. But let's gain full control (and understanding) of the web application by creating a Vaadin project in a very different way—a more fine-grained, controlled way.

A Vaadin application is, at the end of the day, a Java application packaged as a WAR file. You can think of it as a standard web application in which you drop some JARs that allow you to build a web UI using the Java Programming Language instead of HTML and JavaScript. Is it as simple as dropping some JARs into your Java project? Let's find out!

Use the maven-archetype-webapp to generate a simple Java web application by executing the following on the command line:

mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-webapp

Use the following properties when prompted:

  • groupId: packt.vaadin.datacentric.chapter01
  • artifactId: chapter-01
  • version: 1.0-SNAPSHOT
  • package: packt.vaadin.datacentric.chapter01
IDEs such as NetBeans, Eclipse, and IntelliJ IDEA have excellent support for Maven. You should be able to create a new Maven project using the previous archetype in your IDE by providing the corresponding Maven coordinates without using the command line.

Clean up the pom.xml file to make it look like the following:

<project ...>
<modelVersion>4.0.0</modelVersion>

<artifactId>chapter-01</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
</project>
Note that in the code provided with this book, you’ll find a <parent> section in the pom.xml file of the chapter-01 project. This is because all the demo applications of the book have been aggregated into a single Data-centric-Applications-with-Vaadin-8 Maven project for your convenience. You don’t need to add any <parent> section to your project if you are following the steps in this chapter.

Remove the src/main/webapp and src/main/resources directories. This deletes the generated web.xml file which will make Maven complain. To tell it that this was intended, add the following property to your pom.xml file:

    ...
<packaging>war</packaging>

<properties>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
...

Also, add the following properties to configure Maven to use Java 8:

        <maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>

Maven dependencies

At this point, we have a very simple Java project setup that will be packaged as a WAR file. The next natural step is to add the required dependencies or libraries. Vaadin, like many other Java web applications, requires the Servlet API. Add it as follows to the pom.xml file:

    <dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>

Notice that the scope of this dependency is set as provided, which means that a server, or more specifically, a Servlet Container, such as Jetty or Tomcat, will provide the implementation.

Let’s continue by adding the required Vaadin dependencies. First, add the vaadin-bom dependency to your pom.xml file:

     <dependencyManagement>
<dependencies>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-bom</artifactId>
<version>8.3.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
This book uses Vaadin Framework version 8.3.2, the latest production-ready version of the framework at the time of writing.

A Maven BOM, or bill of materials, frees you from worrying about versions of related dependencies; in this case, the Vaadin dependencies. Let's drop these dependencies next. Add the following to your pom.xml file:

    <dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-server</artifactId>
</dependency>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-client-compiled</artifactId>
</dependency>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-themes</artifactId>
</dependency>

There's no need to explicitly set the version for these thanks to the vaadin-bom dependency. We've just added a server-side API (vaadin-server), a client-side engine or widget set (vaadin-client-compiled), and the Valo theme (vaadin-themes).

At this point, you can compile the project by running the following command inside the chapter-01 directory:

mvn clean install

This will download the dependencies to your local Maven repository if you haven't used Vaadin 8.3.2 before.

Servlets and UIs

A Vaadin application in its simplest form is a Servlet that delegates user interface logic to a UI implementation. The vaadin-server dependency includes the Servlet implementation: the VaadinServlet class. Let’s configure one.

Create a new directory with the name java inside the src/main directory.

You might have to tell your IDE that this is a source directory. You will most likely find this by right-clicking the directory and selecting the option to mark it as a source directory. Check the documentation for your IDE for detailed instructions.

Create a new package with the name packt.vaadin.datacentric.chapter01, and add a simple UI implementation inside this package:

public class VaadinUI extends UI {

@Override
protected void init(VaadinRequest vaadinRequest) {
setContent(new Label("Welcome to Data-Centric Applications with Vaadin 8!"));
}
}

Add a new WebConfig class to encapsulate everything related to web configuration, and define the VaadinServlet as an inner class:

public class WebConfig {

@WebServlet("/*")
@VaadinServletConfiguration(
ui = VaadinUI.class, productionMode = false)
public static class WebappVaadinServlet extends VaadinServlet {
}
}

The WebappVaadinServlet class must be public static to allow its instantiation by the Servlet Container. Notice how we are configuring /* as the servlet URL mapping using the @WebServlet annotation. This makes the application available at the root of the deployment path. Notice also how the @VaadinServletConfiguration annotation connects the Servlet to the UI implementation, the VaadinUI class we implemented in the previous step.

Maven plugins

You must have used, or at least seen, the Vaadin Maven plugin. It allows you to compile the widget set and theme, among other tasks. When creating a new Vaadin application, though, you don’t have any add-ons, custom client-side components, or themes. This means you don’t need the Vaadin Maven plugin just yet. You can use the default widget set provided by the vaadin-client-compiled dependency.

We can benefit from at least one Maven plugin at this point: the Jetty Maven plugin. Although you can configure most IDEs to use a variety of servers in order to deploy your application during development, the Jetty Maven plugin frees you from further specific configurations, making it simple for developers to choose the tools they prefer. To use the plugin, add the following to the pom.xml file:

<build>
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.3.7.v20160115</version>
</plugin>
</plugins>
</build>

With this in place, you can run the application by creating a new running configuration in your IDE to execute mvn jetty:run. Point your browser to http://localhost:8080 and you should see the application running:

Components and layouts

To get a full picture of the main parts of a Vaadin application, let's do a quick review of some of the most important classes you should already be familiar with. In a Vaadin application, most of the code deals with components and layouts. In a nutshell, you add components such as Label, TextField, CheckBox, ComboBox, and Grid into layouts such as VerticalLayout, FormLayout, GridLayout, HorizontalLayout, and CSSLayout. You can also add layouts into layouts.

During design or development, you might want to explore the available components and layouts in the framework so that you can pick the best for a particular scenario. One way to see all the components and layouts included in the framework is by visiting the Vaadin sampler at: http://demo.vaadin.com/sampler. You can see code examples by clicking the Information icon in the upper right corner of the page:

Listeners and binders

Vaadin applications interact with the server through listeners and binders. Listeners allow you to handle user interaction, while binders allow you to keep values in input components (such as TextField) and domain objects (for example, a custom User class) in sync.

Events and listeners

In a Vaadin application, the behavior is added through listeners. A listener fires an event when the corresponding action happens, usually caused by the interaction of the user with the UI. Two of the most common listeners in Vaadin are ClickListener (for buttons) and ValueChangeListener (for input components). Listeners are usually defined by implementing a functional interface, which allows you to react to an event using a method reference:

protected void init(VaadinRequest vaadinRequest) { 
Button button = new Button("Click this");
button.addClickListener(this::buttonClicked);
}
...
private void buttonClicked(Button.ClickEvent event) {
Notification.show("Thanks for clicking");
}

You can also use a Lambda expression instead:

button.addClickListener(
event -> Notification.show("Thanks for clicking"));

And to make it more readable and testable, extract the listener logic to a new method, passing only what's needed as parameters (in this case, nothing is needed):

protected void init(VaadinRequest vaadinRequest) { 
...
button.addClickListener(event -> buttonClicked());
}
...
private void buttonClicked() {
Notification.show("Thanks for clicking");
}

Data binding

Data binding is typically done through the Binder class. This class allows you to connect the values in one or more fields to Java properties in a domain class. Suppose you have a User class (the domain class) with a password Java String as one of its properties. You can create a TextField and bind its value to the password property as follows:

TextField textField = new TextField(“Email”);
Binder binder = new Binder<User>()
.forField(textField)
.bind(User::getPassword, User::setPassword);

This is a powerful and type-safe way of implementing data binding. Imagine that you, at some point during development, decide to rename the password property in the User class to something like pin. You can use the refactoring tools of your IDE to rename the property, and the IDE will rename the getters, setters, and any code calling these two methods. Of course, you'd have to change the caption "Email" to "PIN" yourself, but that would have also been the case with other binding mechanisms.

Binders are also used to add validators and converters. These can be added using Lambda expressions or method references. For example, the following snippet of code checks that a String has exactly 4 characters and converts it into an integer:

binder.withValidator(s -> s.length() == 4, “Must be 4 characters")
.withConverter(Integer::parseInt, Object::toString);

Resources and themes

The Resource interface and its implementations are the connections between Java code and resources such as images, downloadable files, or embedded content. You have probably used a StreamResource to dynamically generate a file that a user can download or a ThemeResource to display an image in your UI.

A theme, in turn, is a set of static resources used to configure the appearance of a Vaadin application. By default, Vaadin applications use the Valo theme, a powerful set of styles that can be configured using variables.

Widget sets and add-ons

So far, you have been introduced to the most common parts of a Vaadin application. Vaadin is mostly about using an API with Java running on the server side. This Java code defines how the application looks and behaves, but a Vaadin application runs on a browser using HTML 5 and JavaScript. You don't have to write a line of HTML or JavaScript in order to implement a Vaadin application. How is this possible? How does a Java class define the HTML rendered in the browser?

The key to understanding this is the widget set. A widget set is a JavaScript engine running on the client side, which contains all the code required to show components and communicate with the server side. A widget set is generated by compiling a set of Java classes into JavaScript using GWT. These Java classes are provided by the Vaadin Framework and you can add your own if you want to. If you are not using custom client-side components (your own, or those provided by a third-party Vaadin add-on), you can use the already compiled widget set which is included in the vaadin-client-compiled dependency.