Creating a Basic Vaadin Project

Exclusive offer: get 50% off this eBook here
Learning Vaadin

Learning Vaadin — Save 50%

Read this book or eBook to master the full range of Web Development features powered by Vaadin-built RIAs

$29.99    $15.00
by Nicolas Fränkel | December 2011 | Web Services Open Source Web Development

Vaadin is a new Java web framework for making applications look great and perform well, making your users happy. Vaadin promises to make your user interfaces attractive and usable while easing your development efforts and boosting your productivity.

In this article by Nicolas Frankel, author of Learning Vaadin, we will:

  • Learn key concepts behind the Vaadin framework
  • Have an overview of its internal architecture
  • See how to deploy a Vaadin application to a servlet container, be it in an IDE or outside it
  • See how to update the previously developed application with a very simple interaction in order to display "Hello Vaadin!"

 

(For more resources on this topic, see here.)

 

Understanding Vaadin

In order to understand Vaadin, we should first understand what is its goal regarding the development of web applications.

Vaadin's philosophy

Classical HTML over HTTP application frameworks are coupled to the inherent request/response nature of the HTTP protocol. This simple process translates as follows:

  1. The client makes a request to access an URL.
  2. The code located on the server parses request parameters (optional).
  3. The server writes the response stream accordingly.
  4. The response is sent to the client.

All major frameworks (and most minor ones, by the way) do not question this model: Struts, Spring MVC, Ruby on Rails, and others, completely adhere to this approach and are built upon this request/response way of looking at things. It is no mystery that HTML/HTTP application developers tend to comprehend applications through a page-flow filter.

On the contrary, traditional client-server application developers think in components and data binding because it is the most natural way for them to design applications (for example, a select-box of countries or a name text field).

A few recent web frameworks, such as JSF, tried to cross the bridge between components and page-flow, with limited success. The developer handles components, but they are displayed on a page, not a window, and he/she still has to manage the flow from one page to another.

The Play Framework (http://www.playframework.org/) takes a radical stance on the page-flow subject, stating that the Servlet API is a useless abstraction on the request/response model and sticks even more to it. Vaadin's philosophy is two-fold:

  • It lets developers design applications through components and data bindings
  • It isolates developers as much as possible from the request/response model in order to think in screens and not in windows

This philosophy lets developers design their applications the way it was before the web revolution. In fact, fat client developers can learn Vaadin in a few hours and start creating applications in no time.

The downside is that developers, who learned their craft with the thin client and have no prior experience of fat client development, will have a hard time understanding Vaadin as they are inclined to think in page-flow. However, they will be more productive in the long run.

Vaadin's architecture

In order to achieve its goal, Vaadin uses an original architecture. The first fact of interest is that it is comprised of both a server and a client side.

  • The client side manages thin rendering and user interactions in the browser
  • The server side handles events coming from the client and sends changes made to the user interface to the client
  • Communication between both tiers is done over the HTTP protocol.

We will have a look at each of these tiers.

 

Client server communication

Messages in Vaadin use three layers: HTTP, JSON, and UIDL. The former two are completely un-related to the Vaadin framework and are supported by independent third parties; UIDL is internal.

HTTP protocol

Using the HTTP protocol with Vaadin has the following two main advantages:

  1. There is no need to install anything on the client, as browsers handle HTTP (and HTTPS for that matter) natively.
  2. Firewalls that let pass the HTTP traffic (a likely occurrence) will let Vaadin applications function normally.

JSON message format

Vaadin messages between the client and the server use JavaScript Objects Notation (JSON). JSON is an alternative to XML that has the following several differences:

  • First of all, the JSON syntax is lighter than the XML syntax. XML has both a start and an end tag, whereas JSON has a tag coupled with starting brace and ending brace. For example, the following two code snippets convey the same information, but the first requires 78 characters and the second only 63. For a more in depth comparison of JSON and XML, refer to the following URL:

    http://json.org/xml.html <person> <firstName>John</firstName> <lastName>Doe</lastName> </person> {"person" { {"firstName": "John"}, {"lastName": "Doe"} }

    The difference varies from message to message, but on an average, it is about 40%. It is a real asset only for big messages, and if you add server GZIP compression, size difference starts to disappear. The reduced size is no disadvantage though.

  • Finally, XML designers go to great length to differentiate between child tags and attributes, the former being more readable to humans and the latter to machines. JSON messages design is much simpler as JSON has no attributes.

UIDL "schema"

The last stack that is added to JSON and HTTP is the User Interface Definition Language (UIDL). UIDL describes complex user interfaces with JSON syntax.

The good news about these technologies is that Vaadin developers won't be exposed to them.

The client part

The client tier is a very important tier in web applications as it is the one with which the end user directly interacts.

In this endeavor, Vaadin uses the excellent Google Web Toolkit (GWT) framework. In the GWT development, there are the following mandatory steps:

  1. The code is developed in Java.
  2. Then, the GWT compiler transforms the Java code in JavaScript.
  3. Finally, the generated JavaScript is bundled with the default HTML and CSS files, which can be modified as a web application.

Although novel and unique, this approach provides interesting key features that catch the interest of end users, developers, and system administrators alike:

  • Disconnected capability, in conjunction with HTML 5 client-side data stores
  • Displaying applications on small form factors, such as those of handheld devices
  • Development only with the Java language
  • Excellent scalability, as most of the code is executed on the client side, thus freeing the server side from additional computation

On the other hand, there is no such thing as a free lunch! There are definitely disadvantages in using GWT, such as the following:

  • The whole coding/compilation/deployment process adds a degree of complexity to the standard Java web application development.
  • Although a Google GWT plugin is available for Eclipse and NetBeans, IDEs do not provide standard GWT development support. Using GWT development mode directly or through one such plugin is really necessary, because without it, developing is much slower and debugging almost impossible.

    For more information about GWT dev mode, please refer to the following URL: http://code.google.com/intl/en/webtoolkit/doc/latest/DevGuideCompilingAndDebugging.html

  • There is a consensus in the community that GWT has a higher learning curve than most classic web application frameworks; although the same can be said for others, such as JSF.
  • If the custom JavaScript is necessary, then you have to bind it in Java with the help of a stack named JavaScript Native Interface (JSNI), which is both counter-intuitive and complex.
  • With pure GWT, developers have to write the server-side code themselves (if there is any).
  • Finally, if ever everything is done on the client side, it poses a great security risk. Even with obfuscated code, the business logic is still completely open for inspection from hackers.

Vaadin uses GWT features extensively and tries to downplay its disadvantages as much as possible. This is all possible because of the Vaadin server part.

The server part

Vaadin's server-side code plays a crucial role in the framework.

The biggest difference in Vaadin compared to GWT is that developers do not code the client side, but instead code the server side that generates the former. In particular, in GWT applications, the browser loads static resources (the HTML and associated JavaScript), whereas in Vaadin, the browser accesses the servlet that serves those same resources from a JAR (or the WEB-INF folder).

The good thing is that it completely shields the developer from the client-code, so he/she cannot make unwanted changes. It may be also seen as a disadvantage, as it makes the developer unable to change the generated JavaScript before deployment.

It is possible to add custom JavaScript, although it is rarely necessary.

In Vaadin, you code only the server part!

There are two important tradeoffs that Vaadin makes in order achieve this:

  1. As opposed to GWT, the user interface related code runs on the server, meaning Vaadin applications are not as scalable as pure GWT ones. This should not be a problem in most applications, but if you need to, you should probably leave Vaadin for some less intensive part of the application; stick to GWT or change an entirely new technology.

    While Vaadin applications are not as scalable as applications architecture around a pure JavaScript frontend and a SOA backend, a study found that a single Amazon EC2 instance could handle more than 10,000 concurrent users per minute, which is much more than your average application. The complete results can be found at the following URL: http://vaadin.com/blog/-/blogs/vaadin-scalabilitystudy-quicktickets

  2. Second, each user interaction creates an event from the browser to the server. This can lead to changes in the user interface's model in memory and in turn, propagate modifications to the JavaScript UI on the client. The consequence is that Vaadin applications simply cannot run while being disconnected from the server! If your requirements include the offline mode, then forget Vaadin.

Terminal and adapter

As in any low-coupled architecture, not all Vaadin framework server classes converse with the client side. In fact, this is the responsibility of one simple interface:

com.vaadin.terminal.Terminal.

In turn, this interface is used by a part of the framework aptly named as the Terminal Adapter, for it is designed around the Gang of Four Adapter (http://www.vincehuston.org/dp/adapter.html) pattern.

This design allows for the client and server code to be completely independent of each other, so that one can be changed without changing the other. Another benefit of the Terminal Adapter is that you could have, for example, other implementations for things such as Swing applications. Yet, the only terminal implementation provided by the current Vaadin implementation is the web browser, namely com.vaadin.terminal.gwt.server.WebBrowser.

However, this does not mean that it will always be the case in the future. If you are interested, then browse the Vaadin add-ons directory regularly to check for other implementations, or as an alternative, create your own!

Client server synchronization

The biggest challenge when representing the same model on two heterogeneous tiers is synchronization between each tier. An update on one tier should be reflected on the other or at least fail gracefully if this synchronization is not possible (an unlikely occurrence considering the modern day infrastructure).

Vaadin's answer to this problem is a synchronization key generated by the server and passed on to the client on each request. The next request should send it back to the server or else the latter will restart the current session's application.

This may be the cause of the infamous and sometimes frustrating "Out of Sync" error, so keep that in mind.

 

Learning Vaadin Read this book or eBook to master the full range of Web Development features powered by Vaadin-built RIAs
Published: October 2011
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

 

(For more resources on this topic, see here.)

 

Deploying a Vaadin application

Now, we will see how we can put what we have learned to good use.

Vaadin applications are primarily web applications and they follow all specifications of Web Archive artifacts (WARs). As such, there is nothing special about deploying Vaadin web applications. Readers who are familiar with the WAR deployment process will feel right at home!

WAR deployment is dependent on the specific application server (or servlet/JSP container).

Inside the IDE

Creating an IDE-managed server

Although it is possible to export our project as a WAR file and deploy it on the available servlet container, the best choice is to use a server managed by the IDE. It will let us transparently debug our Vaadin application code.

The steps are very similar to what we did with the mock servlet container.

Selecting the tab

First of all, if the Server tab is not visible, then go to the menu Window | Open perspective | Other... and later choose Java EE.

Creating a server

In order to be as simple as possible, we will use Tomcat. Tomcat is a servlet container, as opposed to a full-fledged application server, and only implements the servlet specifications, not the full Java EE stack. However, what it does, it does it so well that Tomcat was the servlet API reference implementation.

Right-click on the Server tab and select New | Server. Open Apache and select Tomcat 6.0 Server. Keep both Server's host name and Server name values and click on Next.

For running Vaadin applications, Tomcat 6.0 is more than enough as compared to Tomcat 7.x. In fact, it can be downloaded and installed with just a push button. If you want to use Tomcat 7.x, then the process is similar, but you will have to download it separately out of Eclipse. Download it from the following URL: http://tomcat.apache.org/download-70.cgi

However, beware that the first stable version of the 7.x branch is 7.0.6.

Now, the following two options are possible:

  1. If you don't have Tomcat 6 installed, then click on Download and install. Accept the license agreement and then select the directory where you want to install it as shown in the following screenshot:

  2. If you already do, just point to its root location in the Tomcat installation directory field.

By default, you should see a warning message telling you that Tomcat needs a Java Development Kit (JDK) and not a Java Runtime Environment (JRE).

A JRE is a subset of the JDK as it lacks the javac compiler tool (along with some other tools such as javap, a decompiler tool). As JSPs are compiled into servlets at runtime and most regular web applications make heavy use of them, it is a standard to choose a JDK to run Tomcat.

The good thing about Vaadin is that it does not use JSP, so we can simply ignore the warning.

Click on the Finish button.

Verifying the installation

At the end of the wizard, there should be a new Tomcat 6.0 server visible under the Servers tab, as shown in the following screenshot. Of course, if you chose another version or another server altogether, that will be the version or server displayed.

Adding the application

As Vaadin applications are web applications, there is no special deployment process.

Right-click on the newly created server and click on the Add and Remove menu entry. A pop-up window opens. On the left side, there is the list of available web application projects that are valid candidates to be deployed on your newly created server. On the right side, there is the list of currently deployed web applications.

Select MyFirstVaadinApp project and click on the Add button. Then, click on Finish.

The application should now be visible under the server.

Launching the server

Select the server and right-click on it. Select the Debug menu entry. Alternatively, you can:

  • Click on the Debug button (the one with the little bug) on the Server tab header
  • Press Ctrl + Alt + d

Each IDE has its own menus, buttons, and shortcuts. Know them and you will enjoy a huge boost in productivity.

The Console tab should display a log similar to the following:

12 janv. 2011 21:14:36 org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal
performance in production environments was not found on the java.library.path:
...
12 janv. 2011 21:14:36 org.apache.tomcat.util.digester.SetPropertiesRule begin
ATTENTION: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting
property 'source' to 'org.eclipse.jst.jee.server:MyFirstVaadinApp' did not find a
matching property.
12 janv. 2011 21:14:36 org.apache.coyote.http11.Http11Protocol init
INFO: Initialisation de Coyote HTTP/1.1 sur http-8080
12 janv. 2011 21:14:36 org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 484 ms
12 janv. 2011 21:14:36 org.apache.catalina.core.StandardService start
INFO: Démarrage du service Catalina
12 janv. 2011 21:14:36 org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.26
12 janv. 2011 21:14:37 org.apache.coyote.http11.Http11Protocol start
INFO: Démarrage de Coyote HTTP/1.1 sur http-8080
12 janv. 2011 21:14:37 org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
12 janv. 2011 21:14:37 org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/21 config=null
12 janv. 2011 21:14:37 org.apache.catalina.startup.Catalina start
INFO: Server startup in 497 ms

 

This means Tomcat started normally.

 

Outside the IDE

In order to deploy the application outside the IDE, we should first have a deployment unit.

Creating the WAR

For a servlet container, such as Tomcat, the deployment unit is a Web Archive, better known as a WAR.

Right-click on the project and select the Export menu | WAR file. In the opening pop up, just update the location of the exported file: choose the webapps directory where we installed Tomcat and name it myfirstvaadinapp.war.

Launching the server

Open a prompt command. Change the directory to the bin subdirectory of the location where we installed Tomcat and run the startup script.

Troubleshooting
If you have installed Tomcat for the first time, then chances are that the following message will be displayed:
Neither the JAVA_HOME nor the JRE_HOME environment variable is defined
At least one of these environment variables is needed to run this program
In this case, set the JAVA_HOME variable to the directory where Java is installed on your system (and not its bin subdirectory!).

The log produced should be very similar to the one displayed by running Tomcat inside the IDE (as shown in preceding section), apart from the fact that Apache Portable Runtime will be available on the classpath and that does not change a thing from the Vaadin point of view.

 

Using Vaadin applications

Vaadin being a web framework, its output can be displayed inside a browser.

Browsing Vaadin

Whatever way you choose to run our previously created Vaadin project, in order to use it, we just have to open one's favorite browser and navigate to http://localhost:8080/myfirstvaadinapp/vaadin. Two things should happen:

  1. First, a simple page should be displayed with the message Hello Vaadin user
  2. Second, the log should output that Vaadin has started

==============================================================
Vaadin is running in DEBUG MODE.
Add productionMode=true to web.xml to disable debug features.
To show debug window, add ?debug to your application URL.
==============================================================

Troubleshooting
In case nothing shows up on the browser screen and after some initial delay an error pop up opens with the following message:
Failed to load the widgetset: /myfirstvaadinapp/VAADIN/widgetsets/com.vaadin.terminal.gwt.DefaultWidgetSet/com.vaadin.terminal.gwt.DefaultWidgetSet.nocache.js?1295099659815
Be sure to add the /VAADIN/* mapping to the web.xml in the section Declare the servlet mapping and redeploy the application.

Out-of-the-box helpers

Before going further, there are two things of interest to know, which are precious when developing Vaadin web applications.

The debug mode

Component layout in real-world business-use cases can be a complex thing to say the least. In particular, requirements about fixed and relative positioning are a real nightmare when one goes beyond Hello world applications, as they induce nested layouts and component combinations at some point.

Given the generated code approach, when the code does not produce exactly what is expected on the client side, it may be very difficult to analyze the cause of the problem. Luckily, Vaadin designers have been confronted with them early on and are well aware of this problem.

As such, Vaadin provides an interesting built-in debugging feature: if you are ever faced with such a display problem, just append ?debug to your application URL. This will instantly display a neat window that gives a simplified tree view of your components/layouts with additional information such as the component class, the internal Vaadin id, the caption, and the width.

Just be aware that this window is not native (it is just an artifact created with the client-side JavaScript). It can be moved with its title bar, which is invaluable if you need to have a look at what is underneath it. Likewise, it can be resized by pressing the Shift key while the cursor is over the debug window.

Although it considerably decreases the debugging time during the development phase, such a feature has no added value when in production. It can even be seen as a security risk as the debug windows displays information about the internal state of Vaadin's component tree.

Vaadin provides the means to disable this feature. In order to do so, just add the following snippet to your WEB-INF/web.xml:

<context-param> <description>Vaadin production mode</description> <param-name>productionMode</param-name> <param-value>true</param-value> </context-param>

Now, if you try the debug trick, nothing will happen.

Production mode is NOT default
As such, it is a good idea to always set the productionMode context parameter from the start of the project, even if you set it to false. Your build process would then set it to true for release versions. This is much better than forgetting it altogether and having to redeploy the webapp when it becomes apparent.

Restart the application, not the server

We have seen in the Vaadin's architecture section that Vaadin's user interface model is sent to the client through UIDL/JSON messages over HTTP. The whole load is sent at the first request/response sequence, when the Application instance is initialized; additional sequences send only DOM updates.

Yet, important changes to the component tree happen often during the development process. As Vaadin stores the UI state in memory on the server side, refreshing the browser does not display such changes.

Of course, restarting the server discards all the states in memory and remedies the problem, but this operation is not free for heavyweight application servers. Although recent releases of application servers emphasize better startup time, it is a time waste; even more so if you need to restart 10 or 15 times per hour, which is not an unlikely frequency at the start of a new application development.

As for the debugging feature, Vaadin provides the means to reload the computed UI through an URL parameter: change your server-side code, wait for the changes to take effect on the server, just append ?restartApplication, and watch the magic happen. Alternatively, if you are already in the debug mode, there is a button labeled Restart app that has the same effect.

Increase performance
You should remove the restartApplication URL parameter as soon as it is not needed anymore. Otherwise, you will re-run the whole initialization/send UI process each time your refresh the browser, which is not welcome.

 

Learning Vaadin Read this book or eBook to master the full range of Web Development features powered by Vaadin-built RIAs
Published: October 2011
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

 

(For more resources on this topic, see here.)

 

Behind the surface

Wow, in just a few steps, we created a brand new application! Granted, it does not do much, to say the least. Yet, those simple actions are fundamental to the comprehension of more advanced concepts. So, let's catch our breath and see what really happened under the hood.

Stream redirection to Vaadin servlet

The URL http://localhost:8080/myfirstvaadinapp/vaadin can be decomposed in the following three parts, each part being handled by a more specific part:

  1. http://localhost:8080 is the concatenation of the protocol, the domain, and the port. This URL is handled by the Tomcat server we installed and started previously, whether inside the IDE or normally.
  2. /myfirstvaadinapp is the context root and references the project we created before. Thus, Tomcat redirects the request to be handled by the webapp.
  3. In turn, /vaadin is the servlet mapping the Vaadin plugin added to the web deployment descriptor when the project was created. The servlet mapping uses the Vaadin servlet, which is known under the logical name My First Vaadin Application. The latter references the com.vaadin.terminal.gwt. server.ApplicationServlet class.

Vaadin request handling

As you can see, there is nothing magical in the whole process: the URL we browsed was translated as a request that is being handled by the ApplicationServlet.service() method, just like any Java EE compliant servlet would do.

To be exact, the service() method is not coded in ApplicationServlet directly, but in its super class, com.vaadin.terminal.gwt.server.AbstractApplicationServlet.

Vaadin's servlet directly overrides service() instead of the whole group of doXXX() methods (such as doGet() and doPost()). This means that Vaadin is agnostic regarding the HTTP method you use. Purists and REST programmers will probably be horrified at this mere thought, but please remember that we are not manipulating HTTP verbs in request/response sequences and instead using an application.

The following are the rough steps on how the Vaadin servlet services the request response model:

  1. Finds out which application instance this request is related to; this means either create or locate the instance. It delegates to the effective implementation of the Vaadin servlet. For example, when using Spring or CDI, the code will locate the Spring/CDI bean.
  2. If the application is not running, Vaadin launches it. For detailed explanations on the application concept, see the next section.
  3. Locates the current window and delegates it to the request handling.
  4. If the need be:
    • Stops the application
    • Or sends initial HTML/JS/CSS to the client that will interact with the server

The initial load time
Be wary of this last step when creating your own applications: an initial screen that is too big in size will generate an important latency followed by a strange update of your client screen. This is generally not wanted:either try to decrease your initial page complexity or use a change manager that will mitigate the user's feelings about it.

What does an application do?

In Vaadin, an application represents the sum of all components organized in windows, layouts, and having a theme applied. The central class representing an application is the com.vaadin.Application class.

Application responsibilities

Application responsibilities include the following:

  • Managing windows: adding and removing them for the windows registry. Windows are first-level container components, and as such, are of utmost importance to all Vaadin applications.
  • Callbacks during the lifecycle of the application: Two such hooks are possible: before starting and after stopping. For example, the following initialization actions are possible:
    • Making a connection to a database
    • Reading properties file
    • These callbacks can replace the Java EE standard —javax.servlet.Servlet-ContextListener— which does the same, in a more Vaadin-oriented way.

  • Setting themes: Vaadin, being an abstraction layer over HTML/JS/CSS, lets you manage your CSS as a single bundle named a theme. As such, you can change the whole look and feel of your applications by a single server-side command.

Two themes are provided out-of-the-box by Vaadin (reindeer and runo). You can also tweak them and reference them under a new theme name or create entirely new themes from scratch. Readers interested into going further on this road can find documentation at the following link:
http://vaadin.com/book/-/page/themes.creating.html

Application configuration

In our first project, having a look at the web deployment descriptor, notice there is an application servlet parameter configured for the Vaadin servlet:

<servlet> <servlet-name>VaadinApplication</servlet-name> <servlet-class> com.vaadin.terminal.gwt.server.ApplicationServlet </servlet-class> <init-param> <param-name>application</param-name> <param-value> com.packt.learnvaadin.MyApplication </param-value> </init-param> </servlet>

As such, there can be only a single Vaadin application configured for each Vaadin servlet.

Application and session

The most important fact about the Application class is that one instance of it is created the first time a user session requests the Vaadin servlet; this instance is stored in the HttpSession related to the session from then on.

In reality, the Application instances are not stored directly in HttpSession, but within a com.vaadin.terminal.gwt.server.WebApplicationContext instance that is stored in the session. There is a 1-n relationship from WebApplicationContext to Application meaning there is a possibility that more than one Application could relate to the same session. You should keep in mind that each session stores one and only one application object for each configured Vaadin servlet.

Vaadin's object model encompasses Application, Window, and AbstractComponent as shown in the following diagram:

Out of memory
Storing the UI state in the session has a major consequence. Great care must be taken in evaluating the number of users and the average load of each user session because the session is more loaded than in traditional Java EE web applications, thus greater is the risk of java.lang.OutOfMemoryError.

Scratching the surface

Having said all that, it is time to have a look at the both the source code that was created by the Vaadin plugin and the code that it generated and pushed on the client.

The source code

The source code was taken care of by Vaadin plugin:

import com.vaadin.Application; import com.vaadin.ui.*; public class HelloWorldApp extends Application public void init() { Window mainWindow = new Window("Hello World Application"); Label label = new Label("Greetings, Vaadin user!"); mainWindow.addComponent(label); setMainWindow(mainWindow); }

Though having no prior experience in Vaadin and only armed with some basic concepts, we can guess what the class does. That is the strength of Vaadin, compared to competitor frameworks, it is self-evident!

  • At line 1 of the init() method, we create a new window with a title. Windows are first-class components in Vaadin as they can be the top-most elements.
  • At line 2, we create a new label. Labels are used to display static messages. They are often found in web forms as description for fields. Our label has a specific text. Notice it is displayed in the final screen.
  • At line 3, we add the label to the window. Even when you have no prior experience with component-based development (whether thin or fat client based), it is clear that the label will be displayed in the window.
  • Finally, at line 4, we set the window we created as the main window of the screen, displaying it as a root component. We can check that the window's very title takes place in the HTML <title> element. With most browsers, it is also shown in the browser window title.

The generated code

In your favorite browser, right-clicking and selecting the menu that shows the source will only display JavaScript—gibberish to the inexperienced eye.

In fact, as the UI is generated with GWT, we don't see anything interesting in the HTML source—only the referenced JavaScript and a single

<noscript> tag that handles the case where our browser is not JavaScript-enabled (an unlikely occurrence in our time, to say the least).

 

There is a consensus on the Web that AJAX-powered web applications should degrade gracefully, meaning that if the user deactivates JavaScript, applications should still run, albeit with less user-friendliness. Although a very good practice, most of the time, JavaScript applications will not run at all in this case. GWT and thus Vaadin are no exceptions in this matter.

Of much more interest is the generated HTML/JS/CSS. In order to display it, we will need Google Chrome, Firefox with the Firebug plugin, or an equivalent feature in another browser.

More precisely, locate the following snippet:

<div class="v-app v-theme-reindeer v-app-HelloWorldApp" id="myfirstvaadinappvaadin-627683907"> <div class="v-view" tabindex="1" style=""> <div style="position: absolute; display: none;" class="v-loading-indicator"></div> <div style="overflow: hidden; width: 1680px; height: 54px;" class="v-verticallayout"> <div style="overflow: hidden; margin: 18px; width: 1644px; height: 18px;"> <div style="height: 18px; width: 1644px; overflow: hidden; padding-left: 0px; padding-top: 0px;"> <div style="float: left; margin-left: 0px;"> <div class="v-label" style="width: 1644px;"> Greetings, Vaadin user!</div> </div> </div> <div style="width: 0px; height: 0px; clear: both; overflow: hidden;"></div> </div> </div> </div> </div>

Things of interest

First of all, notice that although only a simple message is displayed on the user screen, Vaadin has created an entire DOM tree filled with

elements that has both style and class attributes. For now, just be aware that:

 

  • The class v-view denotes a window
  • The class v-label indicates a label
  • The class v-verticallayout represents a vertical layout

Although we didn't code a vertical layout per se, standard components cannot be the first-level children of windows. By default, the Window class uses a vertical layout and components added to the window are in fact added to the latter.

Moreover, the vertical layout is not the only child div of the view: there is another one that has v-loading-indicator as a class. You probably did not notice as the UI is very simple, but if you refresh the browser window, there should be a circular loading indicator displayed at the left of the page just before the UI finishes loading:

Be aware that it gives no indication on the progress whatsoever, but it at least lets users know that the application is not ready to be used. Such indicators are added, for free, each time a window instance is set as the main window of an application.

Summary

We saw a few things of importance in this article.

First, we had an overview of the Vaadin's philosophy. Vaadin creates an abstraction over the classic request/response sequence in order for developers to think in "applications" and no more in "pages".

In order to do that, the Vaadin architecture has three main components:

  • The client side: that is JavaScript upon the Google Web Toolkit.
  • The server side that generates the client code. One concept of note on the server side is the terminal one: the terminal is in charge of abstracting over the client side. Should the need arise; we could create an abstraction that is not web-oriented.
  • Communications between the client and the server are implemented with JSON/UIDL messages over the HTTP protocol.

There is nothing special with Vaadin applications, they are simple web archives and are deployed as such. Two tools bundled with Vaadin will prove useful during the development:

  1. The debug window that is very convenient when debugging display and layout-related bugs
  2. How to restart the framework without necessarily restarting the application server

Finally, we somewhat scratched the surface of how it all works and most notably:

  • The handling of an HTTP request by Vaadin
  • The notion of application in the framework
  • The code, both the source generated by the plugin and the HTML structure generated by the former

This article concludes the introduction to Vaadin. It is a big step on the path to learning Vaadin.



About the Author :


Nicolas Fränkel

Nicolas Fränkel operates as a successful Java/Java EE architect with more than 10 years' experience in consulting for different clients.

Based in France, he also practices (or has practiced) as a WebSphere Application Server administrator, a certified Valtech trainer, and a part-time lecturer in different French universities, so as to broaden his understanding of software craftsmanship.

His interests in IT are diversified, ranging from Rich Client Application, to Quality Processes through open source software and build automation. When not tinkering with new products or writing blog posts, he may be found practicing sports: squash, kickboxing, and skiing at the moment. Other leisure activities include reading novels, motorcycles, photography, and drawing, not necessarily in that order.

Books From Packt


Google App Engine Java and GWT Application Development
Google App Engine Java and GWT Application Development

Liferay Beginner’s Guide
Liferay Beginner’s Guide

Apache Solr 3.1 Cookbook
Apache Solr 3.1 Cookbook

Rhomobile Beginner's Guide
Rhomobile Beginner's Guide

Grok 1.0 Web Development
Grok 1.0 Web Development

Ext JS 4 Web Application Development Cookbook
Ext JS 4 Web Application Development Cookbook

Facebook Application Development with Graph API Cookbook
Facebook Application Development with Graph API Cookbook

Spring Roo 1.1 Cookbook
Spring Roo 1.1 Cookbook


Your rating: None Average: 1 (1 vote)

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
B
W
c
g
n
B
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software