Book Image

Spring 5.0 Cookbook

By : Sherwin John C. Tragura
Book Image

Spring 5.0 Cookbook

By: Sherwin John C. Tragura

Overview of this book

The Spring framework has been the go-to framework for Java developers for quite some time. It enhances modularity, provides more readable code, and enables the developer to focus on developing the application while the underlying framework takes care of transaction APIs, remote APIs, JMX APIs, and JMS APIs. The upcoming version of the Spring Framework has a lot to offer, above and beyond the platform upgrade to Java 9, and this book will show you all you need to know to overcome common to advanced problems you might face. Each recipe will showcase some old and new issues and solutions, right from configuring Spring 5.0 container to testing its components. Most importantly, the book will highlight concurrent processes, asynchronous MVC and reactive programming using Reactor Core APIs. Aside from the core components, this book will also include integration of third-party technologies that are mostly needed in building enterprise applications. By the end of the book, the reader will not only be well versed with the essential concepts of Spring, but will also have mastered its latest features in a solution-oriented manner.
Table of Contents (20 chapters)
Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

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

Visit the download page of Apache Tomcat application server https://tomcat.apache.org/download-native.cgi and click the Tomcat 9 link that will lead you to the download page.

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: [email protected]
  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: