100% found this document useful (3 votes)
38 views

(PDF Download) Practical Vaadin: Developing Web Applications in Java 1st Edition Alejandro Duarte Fulll Chapter

ebook

Uploaded by

deniisasaba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
38 views

(PDF Download) Practical Vaadin: Developing Web Applications in Java 1st Edition Alejandro Duarte Fulll Chapter

ebook

Uploaded by

deniisasaba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Full download test bank at ebookmeta.

com

Practical Vaadin: Developing Web Applications in


Java 1st Edition Alejandro Duarte

For dowload this book click LINK or Button below

https://ebookmeta.com/product/practical-vaadin-
developing-web-applications-in-java-1st-edition-
alejandro-duarte/

OR CLICK BUTTON

DOWLOAD EBOOK

Download More ebooks from https://ebookmeta.com


More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Quantum entanglement engineering and applications F. J.


Duarte

https://ebookmeta.com/product/quantum-entanglement-engineering-
and-applications-f-j-duarte/

Practical Laravel Develop clean MVC web applications


1st Edition Daniel Correa Paola Vallejo

https://ebookmeta.com/product/practical-laravel-develop-clean-
mvc-web-applications-1st-edition-daniel-correa-paola-vallejo/

Primary Mathematics 3A Hoerst

https://ebookmeta.com/product/primary-mathematics-3a-hoerst/

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-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/

Practical Azure Functions: A Guide to Web, Mobile, and


IoT Applications 1st Edition Agus Kurniawan

https://ebookmeta.com/product/practical-azure-functions-a-guide-
to-web-mobile-and-iot-applications-1st-edition-agus-kurniawan/

Practical Web Development 1st Edition Wellens Paul

https://ebookmeta.com/product/practical-web-development-1st-
edition-wellens-paul/

Developing Graphics Frameworks With Java and OpenGL 1st


Edition Lee Stemkoski

https://ebookmeta.com/product/developing-graphics-frameworks-
with-java-and-opengl-1st-edition-lee-stemkoski/

Introducing Play Framework: Java Web Application


Development 2nd Edition Karunakaran

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

ISBN 978-1-4842-7178-0 e-ISBN 978-1-4842-7179-7


https://doi.org/10.1007/978-1-4842-7179-7

© Alejandro Duarte 2021

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 use of general descriptive names, registered names, trademarks,


service marks, etc. in this publication does not imply, even in the
absence of a specific statement, that such names are exempt from the
relevant protective laws and regulations and therefore free for general
use.

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.

This Apress imprint is published by the registered company APress


Media, LLC part of Springer Nature.
The registered company address is: 1 New York Plaza, New York, NY
10004, U.S.A.
To my father. There’s no better teacher than a good father.
Introduction
This book teaches you how to be productive with Java web application
development. Java is the number one programming language and
runtime environment for high-quality, enterprise-ready software in the
industry, and it will remain as such in the years to come. From credit
cards (through Java Card) to remote-controlled rovers searching for
water and life on Mars, Java has proven to be fast, secure, reliable, and
modern.
The rich Java ecosystem provides developers with an army of
libraries, frameworks, tools, patterns, and practices to triumph in the
software development field. One of the soldiers in the Java ecosystem is
Vaadin—an open source web framework that reduces costs by
shortening the development time of business web applications. Vaadin
is a Finnish word that means “reindeer,” and this reindeer’s motto is
“Fight for Simplicity.” Vaadin simplifies web software development by
offering the best developer experience in the market to Java developers
who prefer to code in Java.

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.

Structure of the Book


A picture is worth a thousand words. And mostly so in a book that
explains how to create graphical user interfaces. The book contains
more than 140 screenshots and figures that make the topics easier to
grasp. The book includes example projects that can be run
independently and, in most cases, are formed by independent screens
to reduce the need to remember code from previous chapters or even
sections.
The book contains 13 chapters grouped into four main parts:
1. Chapters 1 and 2 get you started with web development and
Vaadin. You’ll learn about the Web platform technologies, web
servers, and Java web development.

2. Chapters 3–6 cover the fundamentals of Vaadin—the building


blocks that you’ll use to create web user interfaces with the
framework.

3. Chapters 7–11 cover advanced topics such as Server Push , custom


styles, responsive design, and client-side views with TypeScript.

4. Chapters 12 and 13 cover the basics of the Vaadin integrations with


Spring and Jakarta EE and SQL database connectivity using these
frameworks.

This book doesn’t pretend to be a complete reference document


about Vaadin. I made a good effort to explain the concepts using an
informal, relaxed writing style in contrast to the more reference-like
style often required in official product documentation. I’m convinced
that the Vaadin documentation and this book are the perfect mix to
master Vaadin.
For topics not covered in this book or in the official documentation,
I invite you to join the active Vaadin Community on the channels
available at www.vaadin.com .
Acknowledgments
Writing a book is quite an adventure. Although you have a map, the
fine-grained details of the terrain are uncharted. I took on this
adventure fully aware of the fantastic people who, in one way or
another, would walk the journey with me.
I had an outstanding cartographer—the team at Apress. Jonathan
Gennick helped me to make the most out of the journey. Jill Balzano
made sure that my gear worked through the ride. Andres Sacco pointed
out the immediate dangers and suggested safer pathways.
Writing this book would have been impossible without the almost
unconditional support from Vaadin Ltd. This extraordinary company
allowed me to use a substantial part of my work time to write the draft.
Marcus Hellberg made sure to clear up many of the obstacles I would
have never detected by gazing at the map. My teammates, especially
Mikael Sukoinen and Luis Gutierrez, watched my back and told
inspiring stories every Monday at 5 p.m.
When you take on an adventure like this, the stories that many
other adventurers have told you come to mind and inspire you. In every
paragraph that forms the chapters of this book, there is a software
developer with whom I interacted before. Sami Ekblad, Matti Tahvonen,
Leif Å strand, Petter Hö lmströ m, Jani Laakso, Geovanny Mendoza,
Ricardo Cantillo, Camilo Gonzales, Yury Niñ o, Julien Monnier, Karan
Biawat, Alexandros Milaios, Orlando Vá squez, Andrea Bosio, Jet Beray,
and many others left a mark in this voyage.
Like in every endeavor that imposes challenges, I was accompanied
by those who provide comfort and love when you need to take a break
to prepare for the next leg of the journey. My parents and siblings, Mari
Vento, Jussi Kalliokorpi, Eva Adolfsson, Noomi Ö rså , Dora Quintero, José
Pabó n, Yenny Bermú dez, Camilo Macias, and Erkki Suikki. To all of you,
thank you!
Table of Contents
Part I: Getting Started
Chapter 1:​The World of Vaadin
A CRUD in One Line of Code
The Web platform
HTML
JavaScript and DOM
CSS
Web Components
Server-Side Technologies
Web Servers
CGI
Servlets
Web Development with Vaadin
Summary
Chapter 2:​Setting Up the Development Environment
Installing the JDK
Installing the IDE
Using the Examples of This Book
Importing the Code in the IDE
Running the Examples
Your First Vaadin Application
Routes and Views
UI Components and Layouts
Events and Listeners
Debugging
Server-Side Debugging
Client-Side Debugging
Summary
Part II: The Fundamentals of Vaadin
Chapter 3:​Layouts
Vertical and Horizontal Layouts
Component Composition
The Composite Class
Implementing Reusable UI Components
Accessing the Component Tree
Padding, Margin, and Spacing
Sizing
Grow
Alignment
Justify-Content Mode
Scrolling
FlexLayout
Direction
Wrap
Alignment
Shrink
Other Layouts
Summary
Chapter 4:​UI Components
Input Components
Text Input
Password Input
Boolean Input
Date and Time Input
Numeric Input
Single Selection Input
Multiple Selection Input
File Upload
Interaction Components
Buttons
How Are Events Sent to the Server?​
Links
Menus
Visualization Components
Notifications and Dialogs
Tabs
Icons
Images
Summary
Chapter 5:​Data Binding
Implementing Data Binding Manually
Implementing the Domain Model
Implementing the View
Implementing the Form
The Binder Helper Class
Defining Bindings Programmatically​
Defining Bindings Using Property Names
Using Automatic Binding
Defining Bindings for Nested Properties
Data Conversion and Validation
Using Converters
Implementing Validation Rules
Using Jakarta Bean Validation
Summary
Chapter 6:​The Grid Component
Adding Columns
Managing Columns by Key
Defining Columns with ValueProvider
Adding Rows
In-Memory Data
Lazy Loading
Sorting
Handling Row Selection
Adding UI Components to Cells
Component Columns
Item Details
Exporting to CSV
Summary
Part III: Advanced Features
Chapter 7:​Multiview Navigation and Routing
Routes
Defining Routes at Runtime
Router Layouts
Navigation Lifecycle
Before Enter Observer
Before Leave Observer
URL Parameters
URL Templates
Typed Parameters
Query Parameters
Updating the Page Title
Summary
Chapter 8:​Server Push
When Is Server Push Used?​
How Server Push Works
Performing Asynchronous UI Updates
Automatic Server Push Updates
Manual Server Push Updates
Using Thread Pools
WebSocket vs.​Long Polling
Summary
Chapter 9:​The Element API
Creating DOM Elements
Creating Custom Components
Styling
Mixin Interfaces
Handling Events
JavaScript Integration
Adding JavaScript to a Vaadin Application
Invoking JavaScript from Java
Invoking Java from JavaScript
Summary
Chapter 10:​Custom Styles and Responsiveness
Built-In Themes
Using Theme Variants
Using Component Variants
Styling with CSS
Importing CSS Files
Using Lumo Theme Properties
Adding CSS Classes to UI Components
Styling Shadow DOM
Responsive Web Design
FormLayout
AppLayout
CSS Media Queries
Summary
Chapter 11:​Client-Side Views with TypeScript
Vaadin Flow vs.​Vaadin Fusion
Quick Introduction to TypeScript
Installing the TypeScript Compiler
Implementing “Hello, World” in TypeScript
Static Typing
Web Components with Lit
Creating a New Lit Project
Creating a “Hello, World” Web Component
Client-Side Views with Vaadin Fusion
Enabling Client-Side Bootstrapping
Adding a Client-Side View
Adding Vaadin Components
Event Listeners
Reactive Views
A Word on Offline Capabilities
Summary
Part IV: Integrations and Database Connectivity
Chapter 12:​Spring Boot
Creating a New Spring Boot Project
Creating a New Database
Configuring the Database Connection
Implementing an Entity
Adding a Repository
Inversion of Control and Dependency Injection
Implementing a CRUD
Summary
Chapter 13:​Jakarta EE
Creating a New Jakarta EE Project
Creating a New Database
Configuring the Database Connection
Implementing an Entity
Adding a Repository
Contexts and Dependency Injection
Implementing a CRUD
Summary
Index
About the Author
Alejandro Duarte
is a software engineer currently working
for Vaadin Ltd as their Developer
Relations Manager. This is his third book
on Vaadin. Alejandro started to code at
age 13 using the BASIC programming
language on a black screen with a
blinking cursor serving as the IDE. He
quickly moved to C and C++—languages
he still loves and enjoys—and then to
Java during his computer science studies
at the National University of Colombia
from where he graduated. Alejandro
moved to the UK and later to Finland to
foster his career in the open source
software industry. He became one of the
well-known faces in the Vaadin and Java communities, having published
articles and videos with hundreds of thousands of views in official
Vaadin channels and other content portals, and presented technical
topics at international Java conferences and Java User Groups.
Alejandro splits his free time between his passion for the electric guitar
and the photography world. You can contact him through his personal
blog at www.programmingbrain.com .
About the Technical Reviewer
Andres Sacco
has been working as a developer since
2007 in different languages including
Java, PHP, Node.js, and Android. Most of
his background is in Java and the
libraries or frameworks associated with
this language, for example, Spring,
Hibernate, JSF, and Quarkus. In most of
the companies that he worked for, he
researched new technologies in order to
improve the performance, stability, and
quality of the applications of each
company.
Part I
Getting Started
© The Author(s), under exclusive license to APress Media, LLC, part of Springer
Nature 2021
A. Duarte, Practical Vaadin
https://doi.org/10.1007/978-1-4842-7179-7_1

1. The World of Vaadin


Alejandro Duarte1
(1) Turku, Finland

This chapter serves as a general introduction to web development and


the technologies around Vaadin. This is one of the few chapters in
which you will see HTML and JavaScript code (and even the Python
interpreter), I promise.

A CRUD in One Line of Code


When I started my career in web development, I joined a group of
developers in the enrollment department of one of the largest
universities in South America. The department operation was
supported by a web application written in Java with Struts 2 (a Java
web framework), Hibernate (a database persistence framework),
Spring Framework (the enterprise configuration framework or, as we
used to describe it, the glue of the application), and many other
libraries.
Many of the web pages in the application shared a common UI (user
interface) pattern: they all had a form to search data, a table to present
the data, and options to operate on the data. In other words, the
application had tons of Create, Read, Update, and Delete (CRUD ) views.
The code of the application included helpers for implementing these
kinds of views. However, this involved duplicating code—something I
wasn’t very happy about.
I started to research Java web frameworks in hopes of finding ideas
that helped me solve this problem when I discovered Google Web
Toolkit (GWT) . GWT included a Java to JavaScript compiler which
allowed developers to implement web user interfaces in Java rather
than in JavaScript. I enjoyed the innovative approach, and as I learned
more about it, I discovered that there was an even more mature web
framework that used the same philosophy, except it didn’t compile Java
code to JavaScript. Its name, Vaadin.
After some days playing with Vaadin, I relatively quickly
implemented a reusable library to dynamically create CRUD views with
one line of Java. Here’s an example:

GridCrud<User> crud = new GridCrud<>(User.class);

Figure 1-1 shows the type of CRUD views that can be created with
this library.

Figure 1-1 A CRUD view implemented with Vaadin

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.

The Web platform


Sometimes, developing with Vaadin feels like magic. You type a Java
snippet of code that’s supposed to show a button on the browser, and
the button indeed magically appears there. I want to show you that
there’s no such thing as magic in software development. If you
understand the underlying mechanisms, you’ll see there are no tricks,
and you’ll be in a better position to master any technology.
Beside the Java programming language, the fundamental
technologies are those in the Web platform . The Web platform is a set
of programming languages and API standards developed mainly by the
World Wide Web Consortium and implemented by web browsers. This
includes HTTP, HTML, ECMAScript (the standard governing JavaScript),
DOM Events, XMLHttpRequest, CSS, Web Components, Web Workers,
WebSocket, WebAssembly, Geolocation API, Web Storage, and several
others.
It can be daunting to master all these technologies, but the reality is
that you will mostly use three of them directly in everyday web
development: HTML, JavaScript, and CSS. Vaadin abstracts away HTML
and JavaScript (alongside related APIs), so you end up using only Java
and CSS most of the time. However, it’s always good to understand the
underlying technologies at least to some degree.

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>

Most tags are used in pairs. For example:

<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:

<button>Time in the client</button>

The main parts of an HTML document are structured in three tags:


<html>: The root or top-level element of the document
<head>: Metadata about the document to add resources (images,
JavaScript, CSS) or configure things such as the title of the page
(using the <title> tag)
<body>: The renderable content of the document
Opening tags may include attributes. For instance, you can specify
the language of the page by using the lang attribute of the <html>
tag:

<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 HTML doesn’t care about indentations. Developers do, and


some choose to indent the content of the <html> and <body> tags,
while others prefer not to do it. I prefer to not indent these since
they present in almost all documents, and they just shift everything
to the right. However, I do indent the content of the HTML tags inside
the <body> tag for readability. In the previous example, none of
these tags have other tags as content, so there’s nothing to indent
inside the <body> tag. Moreover, most IDEs indent with the style I
used in the example.

If you use a plain text editor (next chapters cover setting up a


development environment) to create a browser-time.html file and open
this file in a web browser, you’ll see something similar to the screenshot
in Figure 1-2.

Figure 1-2 A simple HTML document rendered in a web browser


I encourage you to try this on your computer and experiment with
the code. Try adding tags such as <input> and formatting text with
<b>, <i>, and <code>.

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.

JavaScript and DOM


JavaScript is a multipurpose, prototype-based (allows the creation of
objects without defining classes prior), single-threaded, scripting
programming language with first-class functions. Besides its name and
the Date object (which is a direct port of Java’s java.util.Date
class), JavaScript has nothing to do with the Java language itself.
However, JavaScript is frequently used in conjunction with Java to
develop web applications—Java on the server, JavaScript on the client.
JavaScript is the programming language of the web browsers.
The DOM (Document Object Model ) is a language-independent API
that represents an HTML (or more generally, XML) document as a tree.
Web browsers implement the DOM as a JavaScript API. Figure 1-3
depicts the DOM hierarchy of the HTML document developed in the
previous section.

Figure 1-3 Example of Document Object Model for an HTML document


With the JavaScript DOM API, developers can add, change, and
remove HTML elements and its attributes, enabling the creation of
dynamic web pages. To add JavaScript logic to an HTML document, you
can use the <script> tag:

<!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>

Returning to the HTML document of the previous section, the


JavaScript logic to make the button work can be placed in the time-
button.js file (next to the browser-time.html file) with the following
content:

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);
});

I tried to write the previous JavaScript code as clear as possible for


Java developers. This script gets all the <button> elements in the
document as an array and adds a click listener to the first one
(incidentally, there’s only one button). The click listener is implemented
as a function that gets called when the user clicks the button. This
listener creates a new <p> element using the DOM API and sets its text
content to show the current time. It then appends the newly created
element to the end of the <body> element. The result is shown in
Figure 1-4.
Figure 1-4 A simple JavaScript application running in a web browser

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>

As with JavaScript files, I like to have separate files to define CSS


styles. This is done by using a <link> tag in the <head> section:

<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;
}

Selectors allow targeting by tag name (like in the previous


examples), element ID, attribute values, and others. One of the most
important selectors is the class selector. A class selector allows to target
elements that have a specified value in their class attribute. The
following snippet shows how to add the time-button CSS class to the
button in the example:
<button class="time-button">Time in the
client</button>
A CSS class selector starts with a period followed by the name of the
class to target. To style the button in the previous example, you can use
a rule like the following:

.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.

Figure 1-5 An HTML document rendered with custom CSS styles

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>

Custom elements must have a dash in their names so that browsers


(and you) know it’s not a standard HTML element. There are two things
that are required to be able to use a custom element:
Implement a class that extends HTMLElement (or a specific
element).
Register the new element using
customElements.define(name, constructor).
Here’s how:

class TimeButtonElement extends HTMLElement {

constructor() {
super();
...
}
}

customElements.define("time-button",
TimeButtonElement);

In the constructor, you can define the content of the element by


using this.innerHTML or any functionality available in the DOM API:

let button = document.createElement("button");


button.textContent = "Time in the client";
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);

This creates the button programmatically and appends it to the


custom element. To make the element more flexible for reuse, it’s a
good idea to allow specifying values like the text shown in the button
instead of hardcoding them ("Time in the client"):

button.textContent = this.getAttribute("text");
With this, the button can be used as follows:

<time-button text="Time in the client"></time-


button>

It’s possible to use the component multiple times by just adding


more <time-button> tags to the document. Listing 1-2 shows a full
HTML document that includes two buttons with different texts, and
Listing 1-3 shows the companion time-button.js file that implements
and registers the custom element.

<!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

class TimeButtonElement extends HTMLElement {

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.

Figure 1-7 The client-server architecture over HTTP


Often, web servers are called HTTP servers or application servers,
depending on whether the content that is served is static or dynamic. A
static web server maps URLs to files in the host and sends them when
requested by the browser. A dynamic web server is a static web server,
but it offers developers the possibility to process the hosted files before
serving them.
A web server is software that you can install and run on your
machine. You probably have one (or several) already installed in your
computer. In fact, nearly all Unix platforms (Linux, macOs, FreeBSD, and
others) come out of the box with Python, which in turn includes a
module to easily run an HTTP web server to serve the files in the
current directory. On Windows systems, you’ll have to install Python or,
even better, enable WSL (Windows Subsystem for Linux ) and use the
Windows store to install a Linux distribution such as Ubuntu which
includes Python by default.
Depending on the version of Python, you have to run one of the
following commands to start a web server that allows access through
HTTP to the files in the current directory:

> python -m SimpleHTTPServer 8080


> python3 -m http.server 8080
Tip If you have Node.js installed on your computer, you can
alternatively install an HTTP server with npm install -g
http-server and run it with http-server -p 8080.

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.

Figure 1-8 An HTML document served from a web server

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:

> python -m SimpleHTTPServer 8080 --cgi


> python3 -m http.server 8080 --cgi

With this server, CGI programs should be placed in the cgi-bin


directory when you are using this server. Other web servers may use
different locations and might need the installation of additional
modules to make it work.
Let’s see how to implement a CGI program in Java. Since version 11,
it’s possible to create a Java program that can be executed directly from
the command line:

#!/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!");
}
}

Note The first line in the preceding example is a shebang—a magic


number recognized by Unix-based systems to determine whether a
file is a script or an executable binary. Remember to use the full path
to the java command and make the file executable with chmod +x
server-time. In Windows systems, you can create a .bat file to invoke
the java program. In this case, you’ll need a separate file to place the
Java code.
If you name this file server-time (don’t use the .java extension) and
place it inside the cgi-bin directory (relative to where you started the
Python web server), you’ll be able to access the program from the
browser at http://localhost:8080/cgi-bin/server-time. Figure 1-9 shows
the result.

Figure 1-9 Plain text returned by a CGI program written in Java

The previous example doesn’t really create dynamic content—every


time you request the page, the browser shows exactly the same.
However, it’s easy to understand that the Java program can do more
than returning a hardcoded string. It could instead read an HTML file
and process it to add dynamic content by replacing a placeholder and
then sending the result to STDOUT. This is a technique many web
frameworks use. Here’s a possible implementation:

#!/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;

public class ServerTime {

public static void main(String[] args) throws


IOException {
Path path = Path.of("cgi-bin/template.html");
String template = Files.readString(path,
Charset.defaultCharset());
String content = "Time in the server: " + new
Date();
String output = template.replace("
{{placeholder}}", content);

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>

Figure 1-10 shows the result of invoking the program in the


browser. This is now a dynamic page that shows something different
every time you request it.
Another random document with
no related content on Scribd:
John Dolittle, as usual, went after that problem too with much
energy. He was a very excellent mathematician, was the Doctor. And
one afternoon he sat down with a note book and the Nautical
Almanac and worked out tables which should tell him from the stars
where he was and in what direction he was going. It was curious,
that strange sense of comfort we drew from the stars. They, the
heavenly bodies which from the Earth seemed the remotest, most
distant, unattainable and strangest of objects, here suddenly became
friendly; because, I suppose, they were the only things that really
stayed the same. The stars, as we saw them from the Moon, were
precisely as the stars we had seen from the Earth. The fact that they
were nearly all countless billions of miles away made no difference.
For us they were something that we had seen before and knew.

“We rigged up weather-vanes”

It was while we were at work on devising some contrivance to


take the place of the compass that we made the discovery of the
explosive wood. The Doctor after trying many things by which he
hoped to keep a definite direction had suddenly said one day:
“Why, Stubbins, I have it.—The wind! It always blows steady—
and probably from precisely the same quarter—or at all events with a
regular calculable change most likely. Let us test it and see.”
So right away we set to work to make various wind-testing
devices. We rigged up weather-vanes from long streamers of light
bark. And then John Dolittle hit upon the idea of smoke.
“That is something,” said he, “if we only place it properly, which
will warn us by smell if the wind changes. And in the meantime we
can carry on our studies of the Animal Kingdom and its languages.”
So without further ado we set to work to build fires—or rather
large smoke smudges—which should tell us how reliable our wind
would be if depended on for a source of direction.
THE ELEVENTH CHAPTER
We Prepare to Circle the Moon

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”

Well, we harvested several different kinds. Some wouldn’t burn at


all when we tried them. Others, we found, were pretty fair burners,
but not smoky enough.
With about the fifth kind of wood, I think it was that we tested out,
we nearly had a serious accident. Fire seemed to be (outside of the
traces we had found of the smoke signal apparatus) a thing quite
unusual in the Moon. There were no traces of forest burnings
anywhere, so far as we had explored. It was therefore with a good
deal of fear and caution that we struck matches to test out our fuel.
About dusk one evening the Doctor set a match to a sort of fern
wood (something like a bamboo) and he narrowly escaped a bad
burning. The stuff flared up like gunpowder.
We took him off, Chee-Chee and I, and examined him. We found
he had suffered no serious injuries, though he had had a very close
shave. His hands were somewhat blistered and he told us what to
get out of the little black bag to relieve the inflammation.
We had all noticed that as the wood flared up it sent off dense
masses of white smoke. And for hours after the explosion clouds of
heavy fumes were still rolling round the hills near us.
When we had the Doctor patched up he told us he was sure that
we had stumbled by accident on the fuel that had been used for
making the smoke signals we had seen from Puddleby.
“But my goodness, Doctor,” said I, “what an immense bonfire it
must have been to be visible all that distance!—Thousands of tons of
the stuff, surely, must have been piled together to make a smudge
which could be seen that far.”
“And who could have made it?” put in Chee-Chee.
For a moment there was silence. Then Polynesia spoke the
thought that was in my mind—and I imagine in the Doctor’s too.
“The man who made those torches,” said she quietly, “could
move an awful lot of timber in one day, I’ll warrant.”
“You mean you think it was he who sent the signals?” asked
Chee-Chee, his funny little eyes staring wide open with
astonishment.

“ ‘You mean you think it was he who sent the signals?’ ”

“Why not?” said Polynesia. Then she lapsed into silent


contemplation and no further questioning from Chee-Chee could get
a word out of her.
“Well,” said the monkey at last, “if he did send it that would look
as though he were responsible for the whole thing. It must have
been he who sent the moth down to us—who needed the Doctor’s
assistance and presence here.”
He looked towards John Dolittle for an answer to this suggestion.
But the Doctor, like Polynesia, didn’t seem to have anything to say.
Well, in spite of our little mishap, our wood tests with smoke were
extremely successful. We found that the wind as a direction-pointer
could certainly be relied on for three or four days at a time.
“Of course, Stubbins,” said the Doctor, “we will have to test again
before we set off on our round trip. It may be that the breeze, while
blowing in one prevailing direction now, may change after a week or
so. Also we will have to watch it that the mountain ranges don’t
deflect the wind’s course and so lead us astray. But from what we
have seen so far, I feel pretty sure that we have here something to
take the place of the compass.”
I made one or two attempts later, when Polynesia and Chee-
Chee were out of earshot, to discover what John Dolittle thought
about this idea that it had really been the Moon Man who had
brought us here and not the Animal Kingdom. I felt that possibly he
might talk more freely to me alone on the subject than he had been
willing to with all of us listening. But he was strangely untalkative.
“‘I don’t know, Stubbins,’ said he, frowning”

“I don’t know, Stubbins,” said he, frowning, “I really don’t know. To


tell the truth, my mind is not occupied with that problem now—at all
events, not as a matter for immediate decision. This field of the lunar
Vegetable Kingdom is something that could take up the attention of a
hundred naturalists for a year or two. I feel we have only scratched
the surface. As we go forward into the unknown areas of the Moon’s
further side we are liable to make discoveries of—well, er—who can
tell? When the Moon Man and the Animal Kingdom make up their
minds that they want to get in touch with us, I suppose we shall hear
from them. In the meantime we have our work to do—more than we
can do. . . . Gracious, I wish I had a whole staff with me!—Surveyors,
cartographers, geologists and the rest. Think of it! Here we are,
messing our way along across a new world—and we don’t even
know where we are! I think I have a vague idea of the line we have
followed. And I’ve tried to keep a sort of chart of our march. But I
should be making maps, Stubbins, real maps, showing all the peaks,
valleys, streams, lakes, plateaux and everything.—Dear, dear! Well,
we must do the best we can.”
THE TWELFTH CHAPTER
The Vanity Lilies

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.

“Certainly the plant life became more elaborate and lively”

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.

“The flowers would be about eighteen inches across”

I filled up two of those numerous note books of the Doctor’s on


his conversations with the Vanity Lilies. Often he came back to these
flowers later, when he wanted further information about the Moon’s
Vegetable Kingdom. For as he explained to us, it was in this species
that Plant Life—so far at all events as it was known on either the
Moon or the Earth—had reached its highest point of development.
THE THIRTEENTH CHAPTER
The Flower of Many Scents

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”

The Vanity Lilies, seeing what distress they had caused,


immediately threw out the most soothing lovely scent I have ever
smelled. Clearly they were anxious to please us and cultivate our
acquaintance. Indeed it turned out later from their conversation with
the Doctor (which I took down word for word) that in spite of being a
stationary part of the Moon’s landscape, they had heard of John
Dolittle, the great naturalist, and had been watching for his arrival
many days. They were in fact the first creatures in our experience of
the Moon that made us feel we were among friends.
I think I could not do better, in trying to give you an idea of the
Doctor’s communication with the Vegetable Kingdom of the Moon,
than to set down from my diary, word for word, some parts of the
conversation between him and the Vanity Lilies as he translated
them to me for dictation at the time. Even so, there are many I am
sure who will doubt the truth of the whole idea: that a man could talk
with the flowers. But with them I am not so concerned. Any one who
had followed John Dolittle through the various stages of animal, fish,
and insect languages would not, I feel certain, find it very strange,
when the great man did at last come in touch with plant life of
unusual intelligence, that he should be able to converse with it.
On looking over my diary of those eventful days the scene of that
occasion comes up visibly before my eyes. It was about an hour
before dusk—that is the slight dimming of the pale daylight which
proceeded a half darkness, the nearest thing to real night we ever
saw on the Moon. The Doctor, as we left the camp, called back over
his shoulder to me to bring an extra note book along as he expected
to make a good deal of progress to-night. I armed myself therefore
with three extra books and followed him out.
Halting about twenty paces in front of the lily beds (we had
camped back several hundred yards from them after they had nearly
suffocated Chee-Chee) the Doctor squatted on the ground and
began swaying his head from side to side. Immediately the lilies
began moving their heads in answer, swinging, nodding, waving, and
dipping.

“ ‘Are you ready, Stubbins?’ ”

“Are you ready, Stubbins?” asked John Dolittle.


“Yes, Doctor,” said I, making sure my pencil point would last
awhile.
“Good,” said he.—“Put it down”:
The Doctor—“Do you like this stationary life—I mean, living in the
same place all the time, unable to move?”
The Lilies—(Several of them seemed to answer in chorus)
—“Why, yes—of course. Being stationary doesn’t bother us. We hear
about all that is going on.”
The Doctor—“From whom, what, do you hear it?”
The Lilies—“Well, the other plants, the bees, the birds, bring us
news of what is happening.”
The Doctor—“Oh, do you communicate with the bees and the
birds?”
The Lilies—“Why, certainly, of course!”
The Doctor—“Yet the bees and the birds are races different from
your own.”
The Lilies—“Quite true, but the bees come to us for honey. And
the birds come to sit among our leaves—especially the warblers—
and they sing and talk and tell us of what is happening in the world.
What more would you want?”
The Doctor—“Oh, quite so, quite so. I didn’t mean you should be
discontented. But don’t you ever want to move, to travel?”
The Lilies—“Good gracious, no! What’s the use of all this running
about? After all, there’s no place like home—provided it’s a good
one. It’s a pleasant life we lead—and very safe. The folks who rush
around are always having accidents, breaking legs and so forth.
Those troubles can’t happen to us. We sit still and watch the world
go by. We chat sometimes among ourselves and then there is
always the gossip of the birds and the bees to entertain us.”
The Doctor—“And you really understand the language of the
birds and bees!—You astonish me.”
The Lilies—“Oh, perfectly—and of the beetles and moths too.”
“He struck a light”

It was at about this point in our first recorded conversation that


we made the astonishing discovery that the Vanity Lilies could see.
The light, as I have told you, was always somewhat dim on the
Moon. The Doctor, while he was talking, suddenly decided he would
like a smoke. He asked the lilies if they objected to the fumes of
tobacco. They said they did not know because they had never had
any experience of it. So the Doctor said he would light his pipe and if
they did not like it he would stop.
So taking a box of matches from his pocket he struck a light. We
had not fully realized before how soft and gentle was the light of the
Moon until that match flared up. It is true that in testing our woods for
smoke fuel we had made much larger blazes. But then, I suppose
we had been more intent on the results of our experiments than on
anything else. Now, as we noticed the lilies suddenly draw back their
heads and turn aside from the flare, we saw that the extra
illumination of a mere match had made a big difference to the
ordinary daylight they were accustomed to.
THE FOURTEENTH CHAPTER
Mirrors for Flowers

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”

“After all, Stubbins,” said he, “just because we ourselves only


have five senses, it doesn’t follow that other creatures can’t have
more. It has long been supposed that certain birds had a sixth
sense. Still, the way those flowers feel light, can tell colors,
movement, and form, makes it look very much as though they had
found a way of seeing—even if they haven’t got eyes. . . . Humph!
Yes, one might quite possibly see with other things besides eyes.”
Going through his baggage that night after our day’s work was
done, the Doctor discovered among his papers an illustrated
catalogue which had somehow got packed by accident. John Dolittle,
always a devoted gardener, had catalogues sent to him from nearly
every seed merchant and nurseryman in England.
“Why, Stubbins!” he cried, turning over the pages of gorgeous
annuals in high glee—“Here’s a chance: if those lilies can see we
can test them with this.—Pictures of flowers in color!”
The next day he interviewed the Vanity Lilies with the catalogue
and his work was rewarded with very good results. Taking the
brightly colored pictures of petunias, chrysanthemums and
hollyhocks, he held them in a good light before the faces of the lilies.
Even Chee-Chee and I could see at once that this caused quite a
sensation. The great trumpet-shaped blossoms swayed downwards
and forwards on their slender stems to get a closer view of the
pages. Then they turned to one another as though in critical
conversation.
Later the Doctor interpreted to me the comments they had made
and I booked them among the notes. They seemed most curious to
know who these flowers were. They spoke of them (or rather of their
species) in a peculiarly personal way. This was one of the first
occasions when we got some idea or glimpses of lunar Vegetable
Society, as the Doctor later came to call it. It almost seemed as
though these beautiful creatures were surprised, like human ladies,
at the portraits displayed and wanted to know all about these foreign
beauties and the lives they led.

“He held them before the lilies”

This interest in personal appearance on the part of the lilies was,


as a matter of fact, what originally led the Doctor to call their species
the Vanity Lily. In their own strange tongue they questioned him for
hours and hours about these outlandish flowers whose pictures he
had shown them. They seemed very disappointed when he told them
the actual size of most earthly flowers. But they seemed a little
pleased that their sisters of the other world could not at least
compete with them in that. They were also much mystified when

You might also like