1. Información general
Vaadin es un marco Java del lado del servidor para crear interfaces de usuario web. Usándolo, podemos crear nuestro front-end usando características de Java.
2. Dependencias y configuración de Maven
Comencemos agregando las siguientes dependencias a nuestro pom.xml :
com.vaadin vaadin-server com.vaadin vaadin-client-compiled com.vaadin vaadin-themes
Las últimas versiones de las dependencias se pueden encontrar aquí: vaadin-server, vaadin-client-compiled, vaadin-themes.
- paquete vaadin-server : incluye clases para manejar todos los detalles del servidor, como sesiones, comunicación con el cliente, etc.
- vaadin-client-compiled : se basa en GWT e incluye los paquetes necesarios para compilar el cliente
- vaadin-themes : incluye algunos temas prefabricados y todas las utilidades para hacer nuestros temas
Para compilar nuestros widgets de Vaadin, necesitamos configurar maven-war-plugin, vaadin-maven-plugin y maven-clean-plugin. Para obtener el pom completo, asegúrese de consultar el archivo pom en el código fuente, al final del tutorial.
Además, también necesitamos agregar el repositorio Vaadin y la gestión de dependencias:
vaadin-addons //maven.vaadin.com/vaadin-addons com.vaadin vaadin-bom 13.0.9 pom import
La etiqueta DependencyManagement controla las versiones de todas las dependencias de Vaadin .
Para ejecutar rápidamente la aplicación, usaremos el complemento Jetty:
org.eclipse.jetty jetty-maven-plugin 9.3.9.v20160517 2 true
La última versión del complemento se puede encontrar aquí: jetty-maven-plugin.
Con este complemento podemos ejecutar nuestro proyecto usando el comando:
mvn jetty:run
3. ¿Qué es Vaadin?
En pocas palabras, Vaadin es un marco de Java para crear interfaces de usuario , con temas y componentes, y muchas opciones de extensibilidad.
El marco también cubre el lado del servidor , lo que significa que cada cambio que realice en la interfaz de usuario se envía inmediatamente al servidor, por lo que en cada momento la aplicación de backend sabe lo que está sucediendo en el front-end.
Vaadin consta de un lado del cliente y del servidor , con el lado del cliente construido sobre el conocido marco de Google Widget Toolkit, y el lado del servidor manejado por VaadinServlet .
4. El servlet
Normalmente, una aplicación Vaadin no utiliza un archivo web.xml ; en su lugar, define su servlet usando anotaciones:
@WebServlet(urlPatterns = "/VAADIN/*", name = "MyUIServlet", asyncSupported = true) @VaadinServletConfiguration(ui = VaadinUI.class, productionMode = false) public static class MyUIServlet extends VaadinServlet {}
En este caso, este servlet está sirviendo contenido desde la ruta / VAADIN .
5. La clase principal
La clase VaadinUI a la que se hace referencia en el servlet debe extender la clase UI del marco y debe anular el método init para completar el arranque de la aplicación con Vaadin habilitado.
El siguiente paso es crear un diseño y agregarlo a un diseño principal de la aplicación:
public class VaadinUI extends UI { @Override protected void init(VaadinRequest vaadinRequest) { VerticalLayout verticalLayout = new VerticalLayout(); verticalLayout.setSpacing(true); verticalLayout.setMargin(true); setContent(verticalLayout); }
6. Jefes de diseño de Vaadin
El marco viene con una serie de administradores de diseño predefinidos.
6.1. VerticalLayout
Apile los componentes en una columna donde el primero agregado está en la parte superior y el último en la parte inferior:
VerticalLayout verticalLayout = new VerticalLayout(); verticalLayout.setSpacing(true); verticalLayout.setMargin(true); setContent(verticalLayout);
Observe cómo las propiedades aquí se toman prestadas libremente de la terminología CSS típica.
6.2. HorizontalLayout
Este diseño coloca cada componente uno al lado del otro de izquierda a derecha es similar al diseño vertical:
HorizontalLayout horizontalLayout = new HorizontalLayout();
6.3. Diseño de cuadrícula
Este diseño coloca cada widget en una cuadrícula, debes pasar como parámetro las columnas y las filas de la cuadrícula:
GridLayout gridLayout = new GridLayout(3, 2);
6.4. FormLayout
El diseño del formulario coloca el título y el componente en dos columnas diferentes y puede tener indicadores opcionales para los campos obligatorios:
FormLayout formLayout = new FormLayout();
7. Componentes de Vaadin
Ahora que se maneja el diseño, echemos un vistazo a algunos de los componentes más comunes para construir nuestra interfaz de usuario.
7.1. Etiqueta

La etiqueta, por supuesto, también es muy conocida, y simplemente se usa para mostrar texto:
Label label = new Label(); label.setId("LabelID"); label.setValue("Label Value"); label.setCaption("Label"); gridLayout.addComponent(label);
Después de que creamos el componente, observe el paso crítico de agregarlo al diseño.
7.2. Enlace

El widget de enlace es esencialmente un hipervínculo básico:
Link link = new Link("Baeldung", new ExternalResource("//www.baeldung.com/")); link.setTargetName("_blank");
Observe cómo los valores HTML típicos de un elemento están todos aquí.
7.3. Campo de texto

This widget is used to input text:
TextField textField = new TextField(); textField.setIcon(VaadinIcons.USER);
We can further customize the elements; for example, we can quickly add images to the widgets via the setIcon() API.
Also, note that Font Awesome is shipped out of the box with the framework; it's defined as an Enum, and we can easily make use of it.
7.4. TextArea

As you'd expect, TextArea is available next to the rest of the traditional HTML elements:
TextArea textArea = new TextArea();
7.5. DateField and InlineDateField

This powerful component is used to pick dates; the date parameter is the current date to be selected in the widget:
DateField dateField = new DateField("DateField", LocalDate.ofEpochDay(0));

We can go further and nest it inside a combo box control to save space:
InlineDateField inlineDateField = new InlineDateField();
7.6. PasswordField

This is the standard masked password input:
PasswordField passwordField = new PasswordField();
7.7. RichTextArea

With this component, we can show formatted text, and it provides an interface to manipulate such text with buttons to control the fonts, size, alignment, etc.are:
RichTextArea richTextArea = new RichTextArea(); richTextArea.setCaption("Rich Text Area"); richTextArea.setValue(""); richTextArea.setSizeFull(); Panel richTextPanel = new Panel(); richTextPanel.setContent(richTextArea);
7.8. Button

Buttons are used for capturing user input and come in a variety of sizes and colors.
To create a button we instantiate the widget class as usual:
Button normalButton = new Button("Normal Button");
Changing the style we can have some different buttons:
tinyButton.addStyleName("tiny"); smallButton.addStyleName("small"); largeButton.addStyleName("large"); hugeButton.addStyleName("huge"); dangerButton.addStyleName("danger"); friendlyButton.addStyleName("friendly"); primaryButton.addStyleName("primary"); borderlessButton.addStyleName("borderless"); linkButton.addStyleName("link"); quietButton.addStyleName("quiet");
We can create a disabled button:
Button disabledButton = new Button("Disabled Button"); disabledButton.setDescription("This button cannot be clicked"); disabledButton.setEnabled(false); buttonLayout.addComponent(disabledButton);
A native button that uses the browser's look:
NativeButton nativeButton = new NativeButton("Native Button"); buttonLayout.addComponent(nativeButton);
And a button with an icon:
Button iconButton = new Button("Icon Button"); iconButton.setIcon(VaadinIcons.ALIGN_LEFT); buttonLayout.addComponent(iconButton);
7.9. CheckBox

The check box is a change state element, is checked or is unchecked:
CheckBox checkbox = new CheckBox("CheckBox"); checkbox.setValue(true); checkbox.addValueChangeListener(e -> checkbox.setValue(!checkbox.getValue())); formLayout.addComponent(checkbox);
7.10. Lists
Vaadin has some useful widgets to handle lists.
First, we create a list of our items to be placed in the widget:
List numbers = new ArrayList(); numbers.add("One"); numbers.add("Ten"); numbers.add("Eleven");
The ComboBox is a drop down list:

ComboBox comboBox = new ComboBox("ComboBox"); comboBox.addItems(numbers); formLayout.addComponent(comboBox);
The ListSelect vertically places items and uses a scroll bar in case of overflow:

ListSelect listSelect = new ListSelect("ListSelect"); listSelect.addItems(numbers); listSelect.setRows(2); formLayout.addComponent(listSelect);
The NativeSelect is like the ComboBox but have the browser look and feel:

NativeSelect nativeSelect = new NativeSelect("NativeSelect"); nativeSelect.addItems(numbers); formLayout.addComponent(nativeSelect);
The TwinColSelect is a dual list where we can change the items between these two panes; each item can only live in one of the panes at a time:

TwinColSelect twinColSelect = new TwinColSelect("TwinColSelect"); twinColSelect.addItems(numbers);
7.11. Grid
The grid is used to show data in a rectangular way; you have rows and columns, can define header and foot for the data:

Grid grid = new Grid(Row.class); grid.setColumns("column1", "column2", "column3"); Row row1 = new Row("Item1", "Item2", "Item3"); Row row2 = new Row("Item4", "Item5", "Item6"); List rows = new ArrayList(); rows.add(row1); rows.add(row2); grid.setItems(rows);
The Row class above is a simple POJO we've added to represent a row:
public class Row { private String column1; private String column2; private String column3; // constructors, getters, setters }
8. Server Push
Another interesting feature is an ability to send messages from the server to the UI.
To use server push, we need to add the following dependency to our pom.xml:
com.vaadin vaadin-push 8.8.5
The latest version of the dependency can be found here: vaadin-push.
Also, we need to add the @Push annotation to our class representing UI:
@Push @Theme("mytheme") public class VaadinUI extends UI {...}
We create a label to capture the server push message:
private Label currentTime;
We then create a ScheduledExecutorService that sends the time from the server to the label:
ScheduledExecutorService scheduleExecutor = Executors.newScheduledThreadPool(1); Runnable task = () -> { currentTime.setValue("Current Time : " + Instant.now()); }; scheduleExecutor.scheduleWithFixedDelay(task, 0, 1, TimeUnit.SECONDS);
The ScheduledExecutorService is running on the server side of the application and every time it runs, the user interface gets updated.
9. Data Binding
We can bind our user interface to our business classes.
First, we create a Java class:
public class BindData { private String bindName; public BindData(String bindName){ this.bindName = bindName; } // getter & setter }
Then we bind our class that has a single field to a TextField in our user interface:
Binder binder = new Binder(); BindData bindData = new BindData("BindData"); binder.readBean(bindData); TextField bindedTextField = new TextField(); binder.forField(bindedTextField).bind(BindData::getBindName, BindData::setBindName);
First, we create a BindData object using the class we created before, then the Binder binds the field to the TextField.
10. Validators
We can create Validators to validate the data in our input fields. To do that, we attach the validator to the field we want to validate:
BindData stringValidatorBindData = new BindData(""); TextField stringValidator = new TextField(); Binder stringValidatorBinder = new Binder(); stringValidatorBinder.setBean(stringValidatorBindData); stringValidatorBinder.forField(stringValidator) .withValidator(new StringLengthValidator("String must have 2-5 characters lenght", 2, 5)) .bind(BindData::getBindName, BindData::setBindName);
Then we validate our data before we use it:
Button buttonStringValidator = new Button("Validate String"); buttonStringValidator.addClickListener(e -> stringValidatorBinder.validate());
In this case, we are using the StringLengthValidator that validates the length of a String but Vaadin provides other useful validators and also allows us to create our custom validators.
11. Summary
Of course, this quick writeup barely scratched the surface; the framework is much more than user interface widgets, Vaadin provides all you need for creating modern web applications using Java.
Y, como siempre, el código se puede encontrar en Github.