Up and running with Vaadin in 10 minutes

Web applications have become commonplace during recent years. Users have come to expect apps that offer a rich set of features with the same kind of performance as traditional desktop software. Simple websites simply don’t cut it anymore.

For developers, building a web app isn’t always straightforward. From configuring development environment to learning the intricacies of network architectures and security, getting even a simple web app up and running can be time-consuming.

Vaadin is a framework designed to help developers build rich, high-performing web applications quickly and efficiently. It’s made with Java, a language familiar to scores of developers, and has a programming model similar to ones used when developing desktop applications. What all this means is that you can get up and running with Vaadin quite quickly.

Vaadin comes with a example application to help you get started. In this tutorial, we will demonstrate how to install Vaadin and expand the sample app with some new functionality. All in about 10 minutes.

Step 1: Create a Vaadin project using Maven (2 minutes)

There are several ways to install and start using Vaadin. We’ll be using Maven, as you can download, install and create a new project using a single command.

At the command line, copy and paste the following:

 mvn archetype:generate 
   -DarchetypeGroupId=com.vaadin 
   -DarchetypeArtifactId=vaadin-archetype-application 
   -DarchetypeVersion=7.1.6 
   -Dpackaging=war

Hit enter and Vaadin will start creating a new project. During this process, you be asked to enter values for the following properties:

  • groupID: an ID for your project, also used for naming Java packages. It’s convention to use a reversed domain name, e.g. fi.helsinki.cs.
  • artifactID: an ID for your project. For this tutorial, we’ll use hello-world.
  • version: a version number for your project, e.g. 1.0.
  • package: for the purpose of this tutorial, you can leave this blank

Note: more information on these properties, as well and other ways of downloading and installing Vaadin, can be found in the Book of Vaadin, a comprehensive reference for the framework.

Once you’ve executed the command you’re ready to compile and test the hello-world project!

Step 2: Compiling, packaging and running the hello-world project (1–6 minutes)

Before running the example app, we need to compile and package it. cd into the project directory (it’s hello-world if you set hello-world as your artifactID). Then type:

mvn package

Depending on your machine, the process might take a couple of minutes. Grab a coffee in the mean time!

Once the package command has finished, the app can be run by issuing the command

mvn jetty:run

Make sure you are in the project directory before you issue the command; it won’t work otherwise. Once the Jetty server has started, open a web browser of your choice and go to http://localhost:8080/hello-world to see the example app in action.

The app consists of one button, Click Me, which outputs Thank you for clicking each time you press it. However, there is no way to remove the text without reloading the page. For the final part of this tutorial, we will modify the underlying code to include this functionality.

Step 3: Adding functionality to the hello-world project (5 minutes)

If you look in the project directory, you’ll see two subdirectories, src and target, and a file called pom.xml. The application source code is in src; open it, go to main and then java.

In the java directory you will find a directory structure created based on the groupID you specified earlier. Follow the subdirectories until you see a file called MyVaadinUI.java. Open it in you favourite text editor.

Take a look at the init(VaadinRequest request) method. This method specifies the layout and functionality of the example app you ran earlier. Specifically, the method creates a VerticalLayout, adds a Button called button to it, and adds a ClickListener to button. When the user clicks the button, a label containing the text Thank you for clicking is created and added to the layout.

Time to add functionality to clear the text. If we take a look at the Vaadin API under the VerticalLayout class we can see that there is a method called removeComponent(Component c) that allows us to remove components from the layout (actually, the method is inherited from the AbstractOrderedLayout class). The method takes one parameter, a reference to the component to be removed. In order to keep track of–and be able to remove–all the Label components that have been added to the layout, we need to store references to them somewhere. We’ll use an ArrayList for this purpose.

Add the ArrayList right after the line where the VerticalLayout is created:

final ArrayList<Label> labels = new ArrayList<Label>();

Don’t forget to import the java.util package, where ArrayList is located (add the following line after all other import statements at the beginning of the file):

import java.util.ArrayList;

Now that we have a mechanism to store references to labels, let’s add a reference to each label every time the user clicks the Click Me button. Change the old button code (lines 33–38) from this:

Button button = new Button("Click Me");
button.addClickListener(new Button.ClickListener() {
    public void buttonClick(ClickEvent event) {
        layout.addComponent(new Label("Thank you for clicking"));
    }
});

To this:

Button button = new Button("Click Me");
button.addClickListener(new Button.ClickListener() {
    public void buttonClick(ClickEvent event) {
        Label lbl = new Label("Thank you for clicking");
        layout.addComponent(lbl);
        labels.add(lbl);
    }
});

Next, we need some way of knowing when the user wants to clear the text in the app. Let’s add another button, clearButton for this purpose. Once clearButton is clicked, we want to call removeComponent(Component c) for each label stored in our ArrayList (not forgetting to clear the list as well).

At the very end of the init(VaadinRequest request) method, add the following:

Button clearButton = new Button("Clear");
clearButton.addClickListener(new Button.ClickListener() {
    public void buttonClick(ClickEvent event) {
        for(Label l : labels)
            layout.removeComponent(l);
        labels.clear();
    }
});
layout.addComponent(clearButton);

The file of MyVaadinUI.java should now have the following contents (change the fi.helsinki.cs groupID to whatever your groupID is):

package fi.helsinki.cs;

import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import java.util.ArrayList;

@Theme("mytheme")
@SuppressWarnings("serial")
public class MyVaadinUI extends UI
{

    @WebServlet(value = "/*", asyncSupported = true)
    @VaadinServletConfiguration(productionMode = false, ui = MyVaadinUI.class, widgetset = "fi.helsinki.cs.AppWidgetSet")
    public static class Servlet extends VaadinServlet {
    }

    @Override
    protected void init(VaadinRequest request) {
        final VerticalLayout layout = new VerticalLayout();
        final ArrayList<Label> labels = new ArrayList<Label>();
        layout.setMargin(true);
        setContent(layout);

        Button button = new Button("Click Me");
        button.addClickListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
                Label lbl = new Label("Thank you for clicking");
                layout.addComponent(lbl);
                labels.add(lbl);
            }
        });
        layout.addComponent(button);

        Button clearButton = new Button("Clear");
        clearButton.addClickListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
                for(Label l : labels)
                    layout.removeComponent(l);
                labels.clear();
            }
        });
        layout.addComponent(clearButton);
    }

}

Our custom functionality is now added. Package the project and start the Jetty server again to try it out!