The first view and @Route
A screen (view) in Vaadin is a Java class that extends a container component and describes what to show on the page. To open the screen at an address, put the @Route annotation on the class. It is the counterpart of a route in an ordinary web framework, only instead of a controller method you get a whole object with components.
Creating a view
Create a views folder next to Application.java and a file inside it:
// src/main/java/com/example/blog/views/HelloView.java
package com.example.blog.views;
import com.vaadin.flow.component.html.H1;
import com.vaadin.flow.component.html.Paragraph;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
@Route("hello")
@PageTitle("Hello")
public class HelloView extends VerticalLayout {
public HelloView() {
add(new H1("Hello, Vaadin!"));
add(new Paragraph("This page is written in Java."));
}
}Save the file and devtools restarts the server. Open http://localhost:8080/hello — the page shows a heading and a paragraph, and the browser tab says "Hello".
What happens here
| Part | Meaning |
|---|---|
extends VerticalLayout | The screen is a container that places components top to bottom |
@Route("hello") | The screen opens at /hello |
@PageTitle | The text on the browser tab |
add(...) | Adds a component to the container |
H1, Paragraph | Components that wrap the <h1> and <p> tags |
The constructor runs every time the address is opened: each browser tab gets its own view object. Vaadin creates views through Spring, so the constructor can receive services — this will come in handy in the data chapter.
The default address
If @Route has no value, the address comes from the class name: HelloView becomes hello. The classes MainView and Main get the empty address, the site root:
// src/main/java/com/example/blog/views/MainView.java
package com.example.blog.views;
import com.vaadin.flow.component.html.H1;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Route;
@Route
public class MainView extends VerticalLayout {
public MainView() {
add(new H1("Blog admin"));
}
}Now http://localhost:8080/ shows the heading "Blog admin". @Route("") on a class with any name does the same.
How the page is built
In the browser the H1 component turns into a plain <h1> tag, and VerticalLayout into the <vaadin-vertical-layout> web component. You control them only from Java: change the text in a handler and the new text appears for the user.
Common mistake
You forgot @Route or made a typo in the address, so Vaadin cannot find the screen. In development mode the page shows:
Could not navigate to 'hello'Further down the same page Vaadin lists all known routes. Check that the address is in the list and that the class is in the com.example.blog package or one nested in it: Spring looks for classes only there.