Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Spring 5.0 Cookbook

You're reading from   Spring 5.0 Cookbook Recipes to build, test, and run Spring applications efficiently

Arrow left icon
Product type Paperback
Published in Sep 2017
Publisher Packt
ISBN-13 9781787128316
Length 670 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Sherwin John C. Tragura Sherwin John C. Tragura
Author Profile Icon Sherwin John C. Tragura
Sherwin John C. Tragura
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Getting Started with Spring FREE CHAPTER 2. Learning Dependency Injection (DI) 3. Implementing MVC Design Patterns 4. Securing Spring MVC Applications 5. Cross-Cutting the MVC 6. Functional Programming 7. Reactive Programming 8. Reactive Web Applications 9. Spring Boot 2.0 10. The Microservices 11. Batch and Message-Driven Processes 12. Other Spring 5 Features 13. Testing Spring 5 Components

Installing Tomcat 9 and configuring HTTP/2

Since the focus of request and response connections in Spring 5.0 will be HTTP/2, this book will feature the use of HTTP/2 as the protocol for web communications. In HTTP1.1, each request sent to a server resource corresponds to only one response. If the server resources generated a longer processing time, then all other incoming requests are blocked. Unlike in HTTP/2, a single request-response transaction can contain multiple concurrently open streams to avoid starvation or deadlocks. On the other hand, HTTP/2 has superb performance when it comes to web browsing experience, notwithstanding the security it provides to the simple web applications and complex portals using SSL certificates. But what is appreciated in HTTP/2 is its backwards compatibility with HTTP/1.1, thus HTTP methods, status codes, and header fields can still be managed by HttpServletRequest and HttpServletResponse without any changes.

Getting started

How to do it...

The book will utilize Tomcat 9, which is the only Tomcat distribution that fully supports HTTP/2 without installing lots of third-party tools and modules. The following are the step-by-step details in setting up HTTP/2 in Tomcat 9:

  1. Check if you have installed JDK 1.8 in your system. Tomcat 9 only runs with the latest JDK 1.8 without error logs.
  2. If you have downloaded the zipped version, unzip the folder to the filesystem of the development machine. If you have the EXE or MSI version, double-click the installer and follow the installation wizards. The following details must be taken into consideration:
    1. You can retain the default server startup port (8005), HTTP connector port (8080), and AJP port (8009) or configure according to your own settings.
    2. Provide the manager-gui with the username as packt and its password as packt.
  3. After the installation process, start the server and check whether the main page is loaded using the URL http://localhost:8080/.
  4. If Tomcat 9 is running without errors, it is now time to configure HTTP/2 protocol. Since HTTP/2 uses clear-text type request transactions, it is required that we configure Transport Layer Security (TLS) to use HTTP/2 since many browsers such as Firefox and Chrome do not support clear text. For TLS to work, we need a certificate from OpenSSL. For Windows machines, you can get it from https://slproweb.com/products/Win32OpenSSL.html.
  5. Install the OpenSSL (for example, Win64OpenSSL-1_1_0c.exe) by following the installation wizards. This will be used to generate our certificate signing request (CSR), SSL certificates, and private keys.
  6. Create an environment variable OPENSSL_HOME for your operating system. Register it into the $PATH the %OPENSSL_HOME%/bin.
  7. Generate your private key and SSL certificate by running the following command: openssl req -newkey rsa:2048 -nodes -keyout spring5packt.key -x509 -days 3650 -out spring5packt.crt.
  8. In our setup, the file spring5packt.key is the private key and must be strictly unreachable to clients, but by the server only. The other file, spring5packt.crt, is the SSL certificate that we will be registering both in the server keystore and JRE keystore. This certificate is only valid for 10 years (3,650 days).
  1. In Step 8, you will be asked to enter CSR information such as:
Country name (two-letter code) [AU]:PH 
State or province name (full name) [Some-State]: Metro Manila 
Locality name (for example, city):Makati City 
Organization name (for example, company) [Internet Widgits  
Pty Ltd]:Packt Publishing 
Organizational unit name (for example, section): Spring 5.0 Cookbook 
Common name (for example, server FQDN or your name): 
Alibata Business Solutions and Training Services 
E-mail address: sherwin.tragura@alibatabusiness.com 
  1. Generate a keystore that will be validated, both by your applications and server. JDK 1.8.112 provides keytool.exe that will be run to create keystores. Using the files in Step 8, run the following command:
keytool -import -alias spring5server -file spring5packt.crt -keystore spring5server.keystore
  1. If this is your first time, you will be asked to create a password of no less than six letters. Otherwise, you will be asked to enter your password. You will be asked if you want to trust the certificate. The message Certificate reply was installed in keystore means you have successfully done the process.
  2. Java JRE must know the certificate in order to allow all the execution of your deployed Spring 5 applications. To register the created certificate into the JRE cacerts, run the following command:
keytool -import -alias spring5server -file spring5packt.crt -keystore "<Java1.8_folder>\Java1.8.112\jre\lib\security\cacerts" -storepass changeit
  
  1. The default password is changeit. You will be asked to confirm if the certificate is trusted and you just type Y or yes. The message Certificate reply was installed in keystore means you have successfully finished the process.
  2. Copy the three files, namely spring5packt.crt, spring5packt.key, and spring5server.keystore to Tomcat's conf folder and JRE's security folder (<installation_folder>\Java1.8.112\jre\lib\security).
  3. Open Tomcat's conf\server.xml and uncomment the <Connector> with port 8443. Its final configuration must be:
<Connector port="8443" 
protocol="org.apache.coyote.http11.Http11AprProtocol" 
maxThreads="150" SSLEnabled="true"> <UpgradeProtocol
className="org.apache.coyote.http2.Http2Protocol"/> <SSLHostConfig honorCipherOrder="false"> <Certificate certificateKeyFile="conf/spring5packt.key"
certificateFile="conf/spring5packt.crt"
keyAlias="spring5server" type="RSA" /> </SSLHostConfig>
</Connector>
  1. Save the server.xml.
  1. Open C:\Windows\System32\drivers\etc\hosts file and add the following line at the end:
 127.0.0.1 spring5server
  1. Restart the server. Validate the setup through running https://localhost:8443. At first your browser must fire a message; Your connection is not secure. Just click Advanced and accept the certificate:
  1. You will now be running HTTP/2.

How it works...

Java 1.8 and Java 1.9 together with Spring 5.0 support HTTP/2 for the advancement of the JEE servlet container. This improvement is part of their JSR 369 specification which highlights the Servlet 4.0 specification. This Spring version is after Java 1.8's advance concurrency and stream support to run its functional and reactive modules. And since the core platform of Spring 5 is reactive, non-blocking and asynchronous, it needs NIO 2.0 threads of Tomcat 9.x's HTTP/2 for its project execution.

Since enabling HTTP/2 requires configuring TLS, browsers such as Firefox and Chrome will be restricted a bit by this TLS when it comes to running applications. These client browsers do not support clear text TCP; thus there is a need for secured HTTP (or HTTPS) which is the only way these browsers can utilize HTTP/2. And since TLS is enabled, there is a need for a keystore certificate that must be recognized by the application servers and accepted by the browsers in order to execute the request URLs.

OpenSSL for Windows is chosen as our certificate generator in creating TLS certificates. The book will use a self-signed certificate only, which is the easiest and most appropriate method so far in order to secure Apache Tomcat 9. This method no longer needs the certificate to be signed by a Certificate Authority (CA).

After generating the certificate, the certificate must be registered to both the keystore of the JRE and the custom keystore (for example, spring5keystore.keystore) of the application server. Keystores are used in the context of setting up the SSL connection in Java applications between client and server. They provide credentials, store private keys and certificates corresponding to the public keys of the applications and browsers. They are also required to access the secured server which usually triggers client authentication. The installed Java has its own keystore, which is <installation_folder>\Java1.8.112\jre\lib\security\cacerts. Always provide the official passwords in adding your certificates to these keystores. JRE has a default changeit password for its keystore.

The advantage of the TLS-enabled Tomcat 9 server is its support to JSR-369, which is the implementation of the Servlet 4.0 container. Moreover, the virtual hosting and multiple certificates are supported for a single connector, with each virtual host able to support multiple certificates. When the request-response transaction happens with HTTP/2, a session with multiple streams or threads of connections is created, as shown in the following code:

MetaData.Request metaData = new MetaData.Request("GET", HttpScheme.HTTP, new HostPortHttpField("spring5server: 8443" + server.getLocalport()), "/", HttpVersion.HTTP_2, new HttpFields()); 
HeadersFrame headersFrame = new HeadersFrame(1, metaData, null, 
true); 
session.newStream(headersFrame, new Promise.Adapter<Stream>(), new PrintingFramesHandler()); 
session.newStream(headersFrame, new Promise.Adapter<Stream>(), new PrintingFramesHandler()); 
session.newStream(headersFrame, new Promise.Adapter<Stream>(), new PrintingFramesHandler()); 

The whole concept of HTTP/2 transporting requests from client to server and responding back to its clients is depicted with the conceptual model as follows:

You have been reading a chapter from
Spring 5.0 Cookbook
Published in: Sep 2017
Publisher: Packt
ISBN-13: 9781787128316
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image