(PDF Download) Practical Vaadin: Developing Web Applications in Java 1st Edition Alejandro Duarte Fulll Chapter
(PDF Download) Practical Vaadin: Developing Web Applications in Java 1st Edition Alejandro Duarte Fulll Chapter
com
https://ebookmeta.com/product/practical-vaadin-
developing-web-applications-in-java-1st-edition-
alejandro-duarte/
OR CLICK BUTTON
DOWLOAD EBOOK
https://ebookmeta.com/product/quantum-entanglement-engineering-
and-applications-f-j-duarte/
https://ebookmeta.com/product/practical-laravel-develop-clean-
mvc-web-applications-1st-edition-daniel-correa-paola-vallejo/
https://ebookmeta.com/product/primary-mathematics-3a-hoerst/
https://ebookmeta.com/product/the-definitive-guide-to-jakarta-
faces-in-jakarta-ee-10-building-java-based-enterprise-web-
applications-2nd-edition-bauke-scholtz-2/
The Definitive Guide to Jakarta Faces in Jakarta EE 10:
Building Java-Based Enterprise Web Applications 2nd
Edition Bauke Scholtz
https://ebookmeta.com/product/the-definitive-guide-to-jakarta-
faces-in-jakarta-ee-10-building-java-based-enterprise-web-
applications-2nd-edition-bauke-scholtz/
https://ebookmeta.com/product/practical-azure-functions-a-guide-
to-web-mobile-and-iot-applications-1st-edition-agus-kurniawan/
https://ebookmeta.com/product/practical-web-development-1st-
edition-wellens-paul/
https://ebookmeta.com/product/developing-graphics-frameworks-
with-java-and-opengl-1st-edition-lee-stemkoski/
https://ebookmeta.com/product/introducing-play-framework-java-
web-application-development-2nd-edition-karunakaran/
Alejandro Duarte
Practical Vaadin
Developing Web Applications in Java
1st ed.
Alejandro Duarte
Turku, Finland
This work is subject to copyright. All rights are solely and exclusively
licensed by the Publisher, whether the whole or part of the material is
concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in
any other physical way, and transmission or information storage and
retrieval, electronic adaptation, computer software, or by similar or
dissimilar methodology now known or hereafter developed.
The publisher, the authors and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, expressed or implied, with respect to the
material contained herein or for any errors or omissions that may have
been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.
Audience
This book is for software developers with a basic or higher knowledge
of the Java programming language who want to build on their Java skills
to create web graphical user interfaces. It’s tailored to those who want
to create web applications without having to code in JavaScript and
HTML and, instead, leverage the power of Java and its ecosystem in the
presentation layer. It’s also a good resource for developers preparing to
take and pass the Vaadin certification exams or who want to strengthen
their expertise with the framework.
Figure 1-1 shows the type of CRUD views that can be created with
this library.
The fact that Vaadin allowed me to code the web user interface
using Java running on the server side was the main reason I decided to
adopt it in many of my future projects. Being able to use the same
programming language in all the layers of the application removed the
associated efforts in context shifting. Similarly, the learning curve that
developers had to go through when they joined a project was almost
flat—if they knew Jvava, they were productive with Vaadin almost
instantly.
The same will happen to you as you go through this book—you’ll
quickly be able to implement web UIs for your Java projects as you
learn Vaadin. By the end of the book, you’ll have the skills to implement
and maintain Vaadin applications and, why not, create and publish your
own reusable libraries like I did with the CRUD library.
Note If you are curious, the CRUD library is open source and
available for free at
https://vaadin.com/directory/component/crud-ui-
add-on.
HTML
HTML (Hypertext Markup Language ) is what browsers use as the
source when they render a web page. Hypertext means text with
hyperlinks. You have probably clicked many hyperlinks before when
you navigated from one page to another. When you see a web page, you
are seeing the rendered version of an HTML document. An HTML
document is a file (in memory or in a hard drive) that consists of tags
and text and, since HTML5, starts with a Document Type Declaration:
<!DOCTYPE html>
<h1>It works!</h1>
In this example, <h1> is the opening tag, and </h1> the closing tag.
The text between the tags is the content of the tag and can also contain
other HTML tags. In the previous example, the text The Web platform is
rendered by browsers using a heading style. There are several levels of
headings, for example, <h2>, <h3>, etc.
HTML tags not only format code but render UI controls like buttons
and text fields. The following snippet of code renders a button:
<html lang="en"></html>
If we put together the previous snippets of code inside the <body>
element, we can form a complete and valid HTML document that all
browsers can render. Listing 1-1 shows a complete and valid HTML
document.
<!DOCTYPE html>
<html lang="en">
<head>
<title>The Web platform</title>
<link rel="stylesheet" href="browser-time.css">
</head>
<body>
<h1>It works!</h1>
<button>Time in the client</button>
</body>
</html>
Listing 1-1 A complete HTML document
Note You can find a comprehensive list of all the tags in HTML on
the Mozilla Developer Network (MDN) website at
https://developer.mozilla.org/en-
US/docs/Web/HTML/Element. In fact, the MDN is an excellent
source for learning everything about the technologies of the Web
platform.
<!DOCTYPE html>
<html>
...
<body>
...
<script>
... JavaScript code goes here ...
</script>
</body>
</html>
I like to have the JavaScript code in separate files. An alternative way
to add JavaScript is by leaving the content of the <script> tag empty
and using the src attribute to specify the location of the file:
<script src="time-button.js"></script>
let buttons =
document.getElementsByTagName("button");
buttons[0].addEventListener("click", function() {
let paragraph = document.createElement("p");
paragraph.textContent = "The time is: " +
Date();
document.body.appendChild(paragraph);
});
CSS
CSS (Cascading Style Sheets ) is a language that allows to configure
fonts, colors, spacing, alignment, and other styling features that dictate
how an HTML document should be rendered. One easy way to add CSS
code to an HTML document is to use a <style> tag in the <head>
element:
<!DOCTYPE html>
<html>
<head>
...
<style>
... CSS code goes here ...
</style>
</head>
...
</html>
<head>
<link rel="stylesheet" href="browser-time.css">
<head>
Tip <link> is one of the tags that doesn’t have an end tag
(</link>). In HTML5, the end tag is not allowed; however,
browsers just ignore </link> or the cargo cult practice of adding a
/ before > when rendering a page.
CSS rules apply styles to the HTML document. Each CSS rule is written
as a selector that targets HTML elements and declarations with the
styles to apply to those elements. For example, the following CSS rule
changes the font of the entire HTML document:
html {
font: 15px Arial;
}
The html part is the selector. Inside braces are the declarations.
There’s only one declaration in this rule, but it’s possible to define
multiple declarations as well. The following CSS rule changes all <h1>
elements to have a full width (100%), a semi-transparent blue
background color, and a padding (space around the element text) of 10
pixels:
h1 {
width: 100%;
background-color: rgba(22, 118, 243, 0.1);
padding: 10px;
}
.time-button {
font-size: 15px;
padding: 10px;
border: 0px;
border-radius: 4px;
}
This rule changes the size of the font to 15 pixels, adds a padding of
10 pixels around the text in the button, removes the border, and makes
its corners slightly rounded. Combining these concepts, it’s possible to
style the full HTML document in a separate browser-time.css file:
html {
font: 15px Arial;
}
body {
margin: 30px;
}
h1 {
width: 100%;
background-color: rgba(22, 118, 243, 0.1);
padding: 10px;
}
.time-button {
font-size: 15px;
padding: 10px;
border: 0px;
border-radius: 4px;
}
Figure 1-5 shows the previous CSS rules applied to the HTML
document.
Web Components
Web Components are a set of technologies that allows creating reusable
custom HTML elements. In this section, I’ll introduce you to the main
technology: custom elements. This should be enough for you to
understand the key Web platform concepts and see there’s no magic
really.
A Web Component is a reusable and encapsulated custom tag. The
“Time in the client” button of the example is a good candidate for this
kind of component. It’d be handy to be able to use the component in
multiple HTML documents via a custom tag:
<time-button></time-button>
constructor() {
super();
...
}
}
customElements.define("time-button",
TimeButtonElement);
button.addEventListener("click", function () {
let paragraph = document.createElement("p");
paragraph.textContent = "The time is: " +
Date();
document.body.appendChild(paragraph);
});
this.appendChild(button);
button.textContent = this.getAttribute("text");
With this, the button can be used as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<title>The Web platform</title>
<link rel="stylesheet" href="browser-time.css">
</head>
<body>
<h1>It works!</h1>
<time-button text="Time in the client"></time-
button>
<time-button text="What time is it?"></time-
button>
<script src="time-button.js"></script>
</body>
</html>
Listing 1-2 An HTML document reusing a custom element
constructor() {
super();
let button = document.createElement("button");
button.textContent =
this.getAttribute("text");
button.classList.add("time-button");
button.addEventListener("click", function () {
let paragraph = document.createElement("p");
paragraph.textContent = "The time is: " +
Date();
document.body.appendChild(paragraph);
});
this.appendChild(button);
}
}
customElements.define("time-button",
TimeButtonElement);
Listing 1-3 A custom element implemented in JavaScript (time-button.js)
You only need a text editor and a browser to try this out. I
recommend doing so if you are new to web development. Try creating
these files, placing them in the same directory, and opening the HTML
file in a web browser. Make sure you understand what’s going on before
continuing. The client-side step of the journey ends with Figure 1-6
which shows a screenshot of the final pure HTML/JavaScript
application developed so far.
Figure 1-6 The final pure client-side web application
Server-Side Technologies
With the fundamentals of the Web platform in place, you can now
approach the not-less-exciting server side of the equation. In short, this
means understanding what a web server is, how to add custom
functionality to a web server, and how to connect the client (browser)
with the web server.
Web Servers
The term web server is used to refer to both hardware and software
entities. In the hardware realm, a web server is a machine that contains
web server software and resources such as HTML documents,
JavaScript files, CSS files, images, audio, video, and even Java programs.
In the software realm, a web server is the software that serves the
resources in the host machine (the hardware web server) to clients
(web browsers) through HTTP (the protocol that browsers
understand). This book uses the software definition of the term web
server. Figure 1-7 shows the main components in a client-server
architecture and the flow of data through requests and responses over
HTTP.
You can request HTML documents using a URL from any device
connected to your network or even the Internet (granted that the
firewall and other security mechanisms don’t prevent access to your
web server). Figure 1-8 shows the example HTML document when I
requested it from my phone (the result you get might be slightly
different depending on the browser and operating system you use).
Notice how I used my IP address to access the file instead of opening it
directly in the browser.
CGI
CGI (Common Gateway Interface ) is one of the simplest ways to serve
dynamic content from a web server. I’ll avoid the discussion on whether
CGI is dead or whether it’s good or not. My aim is to make you take one
step forward toward server-side technologies, and this technology is
easy to understand from a practical point of view.
CGI defines a way to allow web servers to interact with external
programs in the server. These programs can be implemented in any
programming language. CGI maps URLs to these programs. The
external programs communicate with the client using the standard
input (STDIN) and standard output (STDOUT), which in Java are
available through the System.in and System.out objects. The main
difference between a standard program and a CGI program is that the
output should start with a line containing a Content-Type header.
For example, to serve plain text, the output must start with Content-
Type: text/html followed by an empty line followed by the content
of the file to serve.
The Python HTTP server module includes CGI. To enable it, start the
server using the --cgi argument:
#!/usr/bin/java --source 11
public class ServerTime {
public static void main(String[] args) {
System.out.println("Content-Type:
text/plain\n");
System.out.println("It works!");
}
}
#!/usr/bin/java --source 11
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Date;
System.out.println("Content-Type:
text/html\n");
System.out.println(output);
}
}
This program takes the cgi-bin/template.html file, reads its content,
and replaces {{placeholder}} with a string that contains the time
calculated in the server. The template file could be something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<title>CGI Example</title>
</head>
<body>
<h1>It works!</h1>
{{placeholder}}
</body>
</html>
W
e went to a lot of trouble working out how we could best
place these fires so that they should give us the most
satisfactory results. First of all we decided with much care
on the exact position where we would build them. Mostly
they were on bare knolls or shoulders, where they couldn’t spread to
the underbrush and start a bush-fire. Then came the question of fuel:
—What would be the best wood to build them of?
There were practically no dead trees, as I have said. The only
thing to do then was to cut some timber down and let it dry.
This we proceeded to do but did not get very far with it before the
Doctor suddenly had qualms of conscience. Trees that could talk
could, one would suppose, also feel. The thought was dreadful. We
hadn’t even the courage to ask the trees about it—yet. So we fell
back upon gathering fallen twigs and small branches. This made the
work heavier still, because, of course, we needed a great deal of fuel
to have fires big enough to see and smell for any distance.
After a good deal of discussion we decided that this was a thing
which couldn’t be hurried. A great deal depended on its success. It
was a nuisance, truly, but we had just got to be patient. So we went
back into the jungle-lands and set to work on getting out various
samples of woods to try.
It took a longish time, for the Doctor and myself were the only
ones who could do this work. Chee-Chee tried to help by gathering
twigs; but the material we most needed was wood large enough to
last a fair time.
“Mostly they were on bare knolls”
O
f course on a globe larger than that of the Moon we could
never have done as well as we did. When you come to think
of it, one man, a boy, a monkey and a parrot, as a staff for
the exploration of a whole world, makes the expedition
sound, to say the least, absurd.
We did not realize, any of us, when we started out from our first
landing that we were going to make a circular trip of the Moon’s
globe. It just worked out that way. To begin with, we were expecting
every hour that some part of the Animal Kingdom would come
forward into the open. But it didn’t. And still we went on. Then this
language of the trees and flowers came up and got the Doctor going
on one of his fever-heat investigations. That carried us still further.
We always took great care when departing from one district for an
excursion of any length to leave landmarks behind us, camps or
dumps, so that we could find our way back to food and shelter if we
should get caught in a tight place.
In this sort of feeling our way forward Polynesia was most helpful.
The Doctor used to let her off regularly now to fly ahead of us and
bring back reports. That gave us some sort of idea of what we
should prepare for. Then in addition to that, the Doctor had brought
with him several small pocket surveying instruments with which he
marked on his chart roughly the points at which we changed course
to any considerable extent.
“We always took care to leave landmarks behind us”
In the earlier stages of our trip we had felt we must keep in touch
with the first fruit section we had met with, in order to have a supply
of vegetables and fruits to rely on for food. But we soon discovered
from Polynesia’s scouting reports, that other wooded sections lay
ahead of us. To these we sent Chee-Chee, the expert, to investigate.
And when he returned and told us that they contained even a better
diet than those further back, we had no hesitation in leaving our old
haunts and venturing still further into the mysteries of the Moon’s
Further Side.
The Doctor’s progress with the language of the trees and plants
seemed to improve with our penetration into the interior. Many times
we stopped and pitched camp for four or five days, while he set up
some new apparatus and struggled with fresh problems in plant
language. It seemed to grow easier and easier for him all the time.
Certainly the plant life became more elaborate and lively. By this we
were all grown more accustomed to strange things in the Vegetable
Kingdom. And even to my unscientific eyes it was quite evident that
here the flowers and bushes were communicating with one another
with great freedom and in many different ways.
I shall never forget our first meeting with the Vanity Lilies, as the
Doctor later came to call them. Great gaudy blooms they were, on
long slender stems that swayed and moved in groups like people
whispering and gossiping at a party. When we came in sight of them
for the first time, they were more or less motionless. But as we
approached, the movement among them increased as though they
were disturbed by, or interested in, our coming.
I think they were beyond all question the most beautiful flowers I
have ever seen. The wind, regular as ever, had not changed. But the
heads of these great masses of plants got so agitated as we drew
near, that the Doctor decided he would halt the expedition and
investigate.
We pitched camp as we called it—a very simple business in the
Moon, because we did not have to raise tents or build a fire. It was
really only a matter of unpacking, getting out the food to eat and the
bedding to sleep in.
We were pretty weary after a full day’s march. Beyond the lily
beds (which lay in a sort of marsh) we could see a new jungle district
with more strange trees and flowering creepers.
After a short and silent supper, we lay down and pulled the
covers over us. The music of the forest grew louder as darkness
increased. It seemed almost as though the whole vegetable world
was remarking on these visitors who had invaded their home.
And then above the music of the woods we’d hear the drone of
flying, while we dropped off to sleep. Some of the giant insects were
hovering near, as usual, to keep an eye on these creatures from
another world.
I think that of all experiences with the plant life of the Moon that
with the Vanity Lilies was perhaps the most peculiar and the most
thrilling. In about two days the Doctor had made extraordinary strides
in his study of this language. That, he explained to me, was due
more to the unusual intelligence of this species and its willingness to
help than to his own efforts. But of course if he had not already done
considerable work with the trees and bushes it is doubtful if the lilies
could have got in touch with him as quickly as they did.
By the end of the third day Chee-Chee, Polynesia and I were all
astonished to find that John Dolittle was actually able to carry on
conversation with these flowers. And this with the aid of very little
apparatus. He had now discovered that the Vanity Lilies spoke
among themselves largely by the movement of their blossoms. They
used different means of communication with species of plants and
trees other than their own—and also (we heard later) in talking with
birds and insects; but among themselves the swaying of the flower-
heads was the common method of speech.
The lilies, when seen in great banks, presented a very gorgeous
and wonderful appearance. The flowers would be, I should judge,
about eighteen inches across, trumpet-shaped and brilliantly colored.
The background was a soft cream tone and on this great blotches of
violet and orange were grouped around a jet-black tongue in the
center. The leaves were a deep olive green.
But it was that extraordinary look of alive intelligence that was the
most uncanny thing about them. No one, no matter how little he
knew of natural history in general or of the Moon’s Vegetable
Kingdom, could see those wonderful flowers without immediately
being arrested by this peculiar character. You felt at once that you
were in the presence of people rather than plants; and to talk with
them, or to try to, seemed the most natural thing in the world.
A
nother peculiar thing that baffled us completely, when we
first came into the marshy regions of the Vanity Lily’s home,
was the variety of scents which assailed our noses. For a mile
or so around the locality there was no other flower visible; the
whole of the marsh seemed to have been taken up by the lilies and
nothing else intruded on their domain. Yet at least half a dozen
perfumes were distinct and clear. At first we thought that perhaps the
wind might be bringing us scents from other plants either in the
jungle or the flowering heath lands. But the direction of the breeze
was such that it could only come over the sandy desert areas and
was not likely to bring perfumes as strong as this.
It was the Doctor who first hit upon the idea that possibly the lily
could give off more than one scent at will. He set to work to find out
right away. And it took no more than a couple of minutes to convince
him that it could. He said he was sorry he had not got Jip with him.
Jip’s expert sense of smell would have been very useful here. But for
ordinary purposes it required nothing more delicate than an average
human’s nose to tell that this flower, when John Dolittle had
communicated the idea to it, was clearly able to give out at least half
a dozen different smells as it wished.
The majority of these perfumes were extremely agreeable. But
there were one or two that nearly knocked you down. It was only
after the Doctor had asked the lilies about this gift of theirs that they
sent forth obnoxious ones in demonstrating all the scents that they
could give out. Chee-Chee just fainted away at the first sample. It
was like some deadly gas. It got into your eyes and made them run.
The Doctor and I only escaped suffocation by flight—carrying the
body of the unconscious monkey along with us.
“Chee-Chee just fainted away at the first sample”
W
hen the Doctor noticed how the lilies shrank away from the
glow of the matches he became greatly interested in this
curious unexpected effect that the extra light had had on
them.
“Why, Stubbins,” he whispered, “they could not have felt the heat.
We were too far away. If it is the glare that made them draw back it
must be that they have some organs so sensitive to light that quite
possibly they can see! I must find out about this.”
Thereupon he began questioning the lilies again to discover how
much they could tell him of their sense of vision. He shot his hand
out and asked them if they knew what movement he had made.
Every time (though they had no idea of what he was trying to find
out) they told him precisely what he had done. Then going close to
one large flower he passed his hand all round it; and the blossom
turned its head and faced the moving hand all the way round the
circle.
There was no doubt in our minds whatever, when we had finished
our experiments, that the Vanity Lilies could in their own way see—
though where the machinery called eyes was placed in their
anatomy we could not as yet discover.
The Doctor spent hours and days trying to solve this problem.
But, he told me, he met with very little success. For a while he was
forced to the conclusion (since he could not find in the flowers any
eyes such as we knew) that what he had taken for a sense of vision
was only some other sense, highly developed, which produced the
same results as seeing.
“He passed his hand all around it”