In this article, I'll show you how to create the famous Hello, World application using the Java Programming Language and Vaadin 12 (also valid for Vaadin 10 and 11). Get comfortable, make sure you have Maven installed, fire up your favorite IDE, and let's get started!
Start with a starter, obviously
Go to https://vaadin.com/start/latest and select Project Base. This is the most straightforward project starter and serves well as an initial point. Click Download and extract the zip file. You should get a directory with a Maven project in it. Import this project into your favorite IDE (mine is IntellJ IDEA, by the way).
You should get a directory structure that looks similar to the following:
Let's not worry about the resources and webapp subdirectories for now. Also, I want you to get your hands dirty and implement the example app by yourself. However, it turns out the starter includes the MainView class with kind of a Hello, World application in it. So, let's get rid of the code in the MainView class by removing any annotations, extended classes, and code in the constructor. Go ahead and remove code until it looks like the following (or delete the file and create a new one):
The project is ready. Let's add some code to it!
Add UI components to the web page
Think of the MainView class as the web page shown when you request the app in the web browser. Let's start by doing the simplest Hello, World app we can do with Vaadin–a web app that shows a greeting on the screen.
First off, we need the MainView class to be of a type that Vaadin recognizes as a UI component it can deal with. You have many options, but we will extend a popular class called VerticalLayout:
Now the MainView class has more powers. Check in your IDE some of the methods available in VerticalLayout. You can use the autocompletion feature of your IDE to quickly explore what's available:
What is a VerticalLayout, though? A VerticalLayout is a UI component that arranges other UI components (like buttons or grids) in a vertical fashion or a column if you wish. You do this by using the VerticalLayout.add(Component...) method. But first, we need to prepare the component we want to add into the VerticalLayout. Let's use a very simple one: Text. Go ahead and create a new instance of this class inside the constructor:
Now call the add(Component...) method to actually add the text component to the VerticalLayout:
Expose the view as a web page
To serve this class as a web page, you need to tell Vaadin you wish to do so. Doing this is super easy. Just annotate your MainView class with @Route:
The @Route annotation accepts an optional parameter to specify the actual route (the last part of the URL) you want to use to show this view. For example, @Route("hello") would make the view available at http://localhost:8080/hello. However, Vaadin uses a convention with the class name. Since our class is named MainView, Vaadin exposes the view at the context root (http://localhost:8080/). Moreover, if you add a class named CustomersView, for example, Vaadin exposes the view at http://localhost:8080/customers (note how the "View" part in the class name is ignored). Any other names are exposed using the class name. Just remember that you can override this by using the String parameter in the @Route annotation.
Deploy and run the web application
Since we used a Vaadin starter to create the project, the pom.xml file includes the Jetty Maven plug-in which allows you to use Maven to deploy and run the web application in a local Jetty server. The quickest way to run the application is by using a command line terminal and run:
However, I recommend creating a running configuration in your IDE. A running configuration is like a shortcut inside the IDE to execute an action, for example, a Maven command. Most IDEs offer the possibility to create this from a Maven view that shows all the plugins and its corresponding goals. In IntelliJ IDEA it looks like the following:
You can simply double-click the jetty:run option to deploy the app and start the Jetty server, or you can right-click the option to create a running configuration that will be shown on the top of the IDE's window. This last method has the advantage of offering a keyboard shortcut for the running configuration as well.
You can alternatively use any other server that includes a Web Servlet to deploy and run the application. For example Tomcat or GlassFish. We won't cover this topic here. There are plenty of useful resources on the web that explain how to use these servers.
Once the app is compiled, point your browser to http://localhost:8080 to see the result. Keep in mind that the compilation may take some time the first time you are doing it since you might not have all the Maven dependencies in your hard drive, but this is going to be much faster afterward, for both this project and new ones as well. Here's a screenshot of the application:
Add behavior to the web application
Vaadin includes many ready-to-use UI components. There are buttons, combo boxes, grids, check boxes, text fields, charts, and many others. Let's use the TextField and Button classes to add some interactivity to the web application.
Start by creating instances of these two classes in the constructor:
We want to show a personalized greeting containing the name introduced in the text field anytime the user clicks the button. The way you react to user actions (like clicking a button) is by adding listeners. In the case of a Button, a click listener:
Let's use yet another Vaadin UI component to show a message: Notification:
The greeting is not personalized yet. We want to use the name introduced in the text field as part of the greeting. We can get this value by using the TextField.getValue() method. Cannot be easier:
There, you have new components and behavior in your app. We are just missing one last thing–we created and configured UI components, but we never added them into the VerticalLayout. Use the add method to fix this:
Restart the Jetty server and go to http://localhost:8080 to see the changes:
There are many other cool features in Vaadin. I would suggest you continue with the official Vaadin Tutorial at https://vaadin.com/tutorials/getting-started-with-flow which explains how to build a more real-life application. If you want to master Vaadin, I suggest reading the documentation at https://vaadin.com/docs.
I recently got some hard copies of my last book about Vaadin. I love the matte colored look of the cover. Excellent job by Packt Publishing! Anyway, since the feeling of receiving a package with your own books is hard to describe with words, I decided to do it with code.
Although most of the concepts and design ideas that the book covers are valid for any version of Vaadin, I created a Git branch with all the examples migrated to Vaadin 10. At this time, there are certain features that Vaadin 10 doesn't include (yet?) such as Grid editors, Menus, and LAYOUT_COMPONENT_GROUP styles. But besides that, pretty much everything was easy to migrate.
There are some new features in Vaadin 10 that, obviously, I didn't cover in the book–things such as the new Router and the Element API. However, since the book is aimed at developers with basic Vaadin knowledge (i.e., they how to code UIs with the Vaadin Java API), the examples are useful and illustrate techniques you can use in your applications: modularization, authentication, authorization, database connectivity (with JDB, JPA, MyBatis, and jOOQ), CRUD user interfaces design, lazy loading, and reporting with JasperReports.
Keep in mind that this book is not for total beginners. If you don't know what kind of components are available in Vaadin and how to use the basic functionality they provide, you should start with the introduction to Vaadin Flow and the official Vaadin tutorial.
I have to embed YouTube videos or playlists frequently, so I decided to implement this simple tool to generate the HTML code of an embedded responsive YouTube video or playlist:
If you deploy this to a Java server, you'll get the following:
Since the UI code runs on the server side, you can debug it using the tools that your Java IDE of your choice provides. For example, here we are adding a breakpoint in the line that gets invoked when the button is clicked:
These are some of the cool things about Vaadin Flow:
There are more cool features in Vaadin Flow. The following videos show some of them in action:
I'm glad to announce that my second book about Vaadin has been published!
Due to Packt Publishing's guidelines, the space I had for acknowledgments was limited to 500 characters. However, I'd like to share the original draft I wrote for this section:
I'd like to thank the entire team from Packt Publishing; thanks for your support and patience throughout the writing process. Thanks to all the technical reviewers and proofreaders for providing me with valuable feedback from which I have learned a lot. A special thanks to the Vaadin team and its community for producing a terrific open-source web framework and knowledge base with tons of articles and useful resources. I hope this book reciprocally contributes back to the community.
I'd like to single out Joonas Lehtinen, Sami Ekblad, Matti Tahvonen, Marcus Hellberg, and Fredrik Rönnlund, who in one way or another influenced or motivated this book. In addition, many others provided help and motivation throughout the writing process. Specifically, and in no particular order, I'd like to thank Nicole Mattsson, Jet Dario, Noomi Ylä-Lahti, Dora Quintero, Saara Nevala, Marcelo Duarte, Guillermo Alvarez, Goran Atanasovski, Johannes Häyry, Anna Emelyanova, Kari Söderholm, Paul Römer, Ville Ingman, Amahdy Abdelaziz, Sven Ruppert, Eero Mäkelä, Artem Godin, Jan Rucidlo, Julia Toivonen, Ömer Tümer, Binh Bui, Mikko Inkinen, Shridhar Deshmukh, Frederik Raulf, and all my colleagues at Vaadin Ltd.
Thanks to my parents and siblings for being supportive and helpful throughout my life; I genuinely enjoyed writing part of this book with your company. As Shakespeare wrote in King Lear, in this list you are "although the last, not least".
Microservices bring advantages such as independent development and deployment of services, but they come with a cost, mainly, an increase in complexity, brilliantly explained by Dave Kerr in his article The Death of Microservice Madness in 2018, a highly recommended read for everyone evaluating microservices. One of the key technical challenges with microservices which is related to web frameworks is how to create a "mash-up" UI that combines two or more web applications.
I was able to develop an application using Spring Boot with Spring Cloud to show a web page with a CRUD UI on the left and a Twitter feed on the right, both developed with Vaadin:
Running this application requires starting at least 7 processes, 3 orchestration services, 1 back-end service, and 3 web applications:
You can find detailed information about my experiment in this series of articles:
As some of you may already know, I started writing a book about Vaadin 8 for Packt Publishing almost a year ago. After inevitable hindrances and changes in the scope and schedule, the book is almost ready now!
The book is addressed to Java web developers with basic knowledge of the Vaadin Framework 8. If you have followed the tutorial at https://vaadin.com/docs/v8/framework/tutorial.html and have played around with the framework, this book is for you. Of course, more experienced developers can also find interesting ideas in this book.
The book covers topics related to software design such as code organization, modularization, and API design. It also serves as a practical guide to common features in business applications, ranging from authentication and authorization to reporting and CRUD user interfaces.
Here's the outline (chapters) of the book:
I'll announce on twitter and here once the book gets published. Stay tuned!
One of my favorite new features in Vaadin 8 is the Grid::setDataProvider method which makes it remarkably easy to implement lazy loading in Grids. In earlier versions of Vaadin, you had to implement a rather complex Container interface. Vaadin 8 not only removes this interface, but also provides a modern API that takes advantage of many Java 8 features.
In this blog post, you will learn how to implement lazy loading to show a sortable list of people in a Grid component by simply providing two lambda expressions. You can find two “flavors” of the example application: One for people who use Spring (Spring Boot), and one for people who use Java EE (CDI and WildFly Swarm):
What is lazy loading?
Lazy loading is a technique used to delay the loading of resources to the point where it’s actually needed. Say you have a database table with 1000 rows, and you want to show this data in a UI with space for 20 rows at a time. You can query just the first 20 rows and when the user scrolls down the list, then you query the next 20 rows, and so forth. If you fetch all the data from your data source, your app will consume more memory and will take longer to show something on the screen.
When you want to display tons of data, you would probably use Vaadin’s Grid. By default, Grid performs lazy loading between the client and the server, which already improves performance a lot. This means that you have lazy loading out-of-the-box between the Grid component (in the browser) and the web server. How you query your data source is entirely up to you. If you try to fetch all the data at once, then the Grid will only send what’s needed when it’s needed to the client. However, all the data will stay in the memory on the server-side. Fortunately, the Grid class provides the mechanisms to allow you to query your data source in a lazy way. Let’s see how to do it!
The domain model
Suppose you have a domain class like the following:
And a service class like this:
The actual implementation of the methods depends on your specific persistence technologies. You can find a full implementation of the Person and PersonService classes for both Spring and Java EE applications using the links provided in the introduction
Lazy loading functionality with Grid
You obviously need an instance of the PersonService class and a new Grid:
Notice how, in Vaadin 8, Grid is parameterized with the domain type (Person). Now, instead of using the infamous grid.setItems(service.findAll()), you can use the setDataProvidermethod method and pass:
If you read the previous snippet of code, you might have noticed the sortOrders parameter in the first lambda expression. sortOrder is a List of QuerySortOrder objects that you can use to tell your service how to order the data.
The PersonService::findAll method accepts a Map with String keys representing the name of a Java property in the Person class, and a Boolean value telling whether to sort the property in ascending order. So, for this example, you have to translate between a List<QuerySortOrder> and a Map<String, Boolean>. Some Java should do the job:
As you can see, the QuerySortOrder::getSorted method returns a string with the name of the Java property, and the SortOrder::getDirection method (QuerySortOrder extends SortOrder) returns a value from the SortDirection enum.
And that’s it! You can pass this map to the service, so the complete call to the setDataProvidermethod would look like this:
Originally published at vaadin.com.
If you have been following the web development industry in the last years, there’s a good chance that you have at least heard about microservices architectures. Some would say microservices are a specialization of SOA, others that microservices are the same as SOA, or that microservices are SOA done right. In any case, you might be wondering how to take advantage of the knowledge around microservices. Is it a good architecture for your project? How can Vaadin help in microservices architectures?
In this article, I will talk about the role of Vaadin applications in microservices architectures and provide some guidelines to help you decide on when and how to use microservices with Vaadin.
What are microservices architectures?
Microservices architectures are about modularization. The key term in how modularization is done in microservices architectures is the process. Each service, or microservice, runs as a separate process that can be independently deployed. This makes it possible to use heterogenous technologies, to horizontally scale by starting additional instances, to replace parts of a system (a microservice), and to add resiliency mechanisms than run when a part of the system doesn’t work. This might sound like nothing new, but think of microservices architectures as a revamp of existing practices while reading this article.
Another aspect of microservices architectures is that they help in big projects. Amazon, Ebay, and Netflix are often cited as examples where microservices solved architectural problems. On the other hand, each microservice should be “small”. Defining what’s small and what’s not depends on each project, so ask yourself whether your project “feels” too big for your team. If the answer is yes, consider microservices. If the answer is no, don’t use microservices. In any case, you can benefit from the techniques frequently used in microservices architectures. Just remember not to fall into the “nanoservices” antipattern.
Where do UIs fit in the microservices model? It depends on the specific requirements. It might be that a single UI is the best approach to make your microservices available to people. This could mean that the UI is small enough to be developed by a small team of developers, for example. However, sometimes it makes sense to have separate UIs as separate microservices (deployed independently). For example, the system might serve to many business units with heterogeneous groups of users where each UI can be developed independently.
This is probably the best scenario for most projects and Vaadin can easily fit in. Ideally, a UI is all about view logic without any business logic at all. If you can think of the UI as a tool for the data, then providing a single microservice that acts as a human front-end for your project is a good approach in a microservices architecture.
How does a Vaadin application communicate with other microservices? Because your Vaadin code is Java running on the server side, you can consume other microservices using any Java technology to connect to them. There are a few patterns or techniques that you should at least consider when consuming microservices from a single Vaadin UI.
First, use a service registration and discovery mechanism. This allows the clients of a service to locate services in environments where the exact location of a service might dynamically change. Usually, client microservices will consult a centralized registry for the location of a microservice.
Second, use an API gateway when a client needs to invoke calls to several microservices with probably different communication protocols. Not only might this reduce network traffic, but also reduce the complexity of the client code. However, if your microservices are running on the same network, the API gateway might not be necessary when using the same connection protocols among them. In this situation, a Vaadin UI probably has a strong and fast network connection to the microservices and caching can be done at the UI level (and it’s often done somewhat automatically, for example in Grid rows).
Could this become a big monolith? Maybe. Not all monoliths are bad, though. But, if you really think you’ll have to face the typical problems associated with big monoliths in your Vaadin UI, you can consider splitting it into several individual projects.
Some authors and developers advocate for creating one UI per microservice. Before going this way, carefully think if this would be beneficial for your project. Software architecture should not be a goal but a tool. To fully harness the benefits of a microservices architecture, each microservice should work independently. The ideal scenario when having multiple Vaadin microservices is that each one can be visualized independently, in different browser tabs, for example. There is no need to add special configurations in the case of Vaadin microservices with this approach.
But let’s say you’d like to have separate Vaadin microservices and aggregate them into a “mash-up”. You have three alternatives in this scenario: IFrames, Portlets and UIs embedded directly to a single host page.
The easiest way to integrate several web applications into a single one is by using HTML’s <iframe>tag. You can use Vaadin (BrowserFrame) or any other web technology to develop the mash-up. IFrames are not that bad, however keep in mind there might be some pitfalls.
A good alternative, if you want to go to the route of several Vaadin microservices integrated into a single UI, is Portlets. By using an enterprise portal framework you gain some extra features such as authentication, authorization, and portlets’ inter-communication. Depending on the vendor, it might be possible to fulfill the microservices definition we used in this article, particularly, regarding the ability of microservices to run in separate processes. If you are interested in using portlets, consult the documentation of portal providers regarding support for microservices architectures.
The last alternative is to create a mashup which embeds multiple external UIs hosted in different servers into a single web page. The host page can be implemented with virtually any technology and can naturally be built with Vaadin Framework, as well. The easiest method is to use the Embedded UI add-on. With it, your code will look something like the following:
This approach has advantages and disadvantages, as well. You can use the Vaadin API to easily create the mash-up, but with this add-on you’ll have to use the same Vaadin theme and the same Vaadin version in all the applications.
When using this add-on, or manually embedding UIs in HTML, you have to enable Cross Origin Resource Sharing (CORS) in your microservices. The Embedded UI add-on contains helpers to achieve this.
Microservices architectures solve problems in big applications by dividing a system in several microservices implemented, deployed, and run independently. Even when the term “microservices” might be considered a buzzword, I’d suggest embracing it and taking advantage of the modernized techniques that the microservices movement is generating. Even when microservices are used in big systems, you don’t have to be Amazon, Ebay, or Netflix to take advantage of this techniques. I’m working on a hands-on, more down-to-earth, practical guide that shows how to implement a microservices architecture. Stay tuned and be ready to get your hands dirty.
Originally published at vaadin.com.
Some years ago I published the Enterprise-app add-on for Vaadin. The most awarded feature was the CrudComponent class that allowed you could add a CRUD-like interface to any Hibernate entity by writing one line of code. Enterprise-app was (and still is) available for Vaadin 6. I partially migrated it to Vaadin 7, but never really completed the task.
I'm not longer supporting the Enterprise-app add-on, but working in a set of new Vaadin add-ons to replace parts of its functionality. So far I have implemented the Crud UI add-on, a less magical but much more flexible CrudComponent. A key difference with the old one is that it doesn't perform the actual CRUD operations, instead, it delegates the operations to a CrudListener with 4 methods that you have to implement (or alternatively use 4 separte interfaces and lambda expressions or method references). This allows you to use any persistence technology you want.
Suppose you have a JavaBean like the following:
And a "backend" service class like the following:
Then, with the Crud UI add-on, you can create a CRUD web interface with the following code:
There are several configuration options. See the examples on the add-on's page. The following is an example of a CrudComponent with modified configuration settings for Grid's columns, field captions, layout, and validations: