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
Spring 5.0 Cookbook
Spring 5.0 Cookbook

Spring 5.0 Cookbook: Recipes to build, test, and run Spring applications efficiently

Arrow left icon
Profile Icon Sherwin John C. Tragura
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5 (2 Ratings)
Paperback Sep 2017 670 pages 1st Edition
eBook
€8.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Sherwin John C. Tragura
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5 (2 Ratings)
Paperback Sep 2017 670 pages 1st Edition
eBook
€8.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Spring 5.0 Cookbook

Getting Started with Spring

Spring 5.0 is the latest Spring Framework release that highlights Functional Web Framework and Reactive Programming. In this version, all the codes comply with the latest Java 1.8 syntax but the whole framework is designed to support the Java 1.9 Java Development Kit (JDK) in the near future. On the enterprise platform, the framework is supposed to use servlet 3.1 and 4.0 specifications and utilize HTTP/2 to run its applications.

This book will start with how to set up and configure the development environment given the necessary tools and plugins to run Spring 5.0 applications.

In this chapter, you will learn about the following:

  • Installing Java Development Kit 1.8
  • Installing Tomcat 9 and configuring HTTP/2
  • Installing STS Eclipse 3.8 IDE
  • Creating Eclipse projects using Maven
  • Creating Spring STS Eclipse projects using Gradle
  • Deploying Spring projects using Maven
  • Deploying Spring projects using Gradle
  • Installing the MySQL 5.7 database server
  • Installing the MongoDB 3.2 database server

Installing Java Development Kit 1.8

The book will be using JDK 1.8, which has the support to run Spring 5.0. This version of Java supports @FunctionalInterface and lambda expressions, which are necessary concepts being showcased in this framework. A @FunctionalInterface is an interface with exactly one abstract method that may lead to its instantiation through lambda expressions. Lambda expressions are used to implement anonymous inner classes, avoiding too much bulk in the codes.

Moreover, JDK 1.8 has java.util.stream APIs that can work with collections and NIO 2.0, using stream operations such as filter, map, and reduce. These stream APIs work in sequential and parallel executions. In the area of concurrency, this JDK provides some very essential enhancements on ConcurrentHashMap for its forEach, forEachEntry, forEachKey, forEachValue, compute, merge, reduce, and search methods. Also some changes were done on the object creation of CompletableFuture and Executors.

Getting started

How to do it...

To download JDK 1.8, perform the following steps:

  1. Visit the preceding Oracle's page for downloads.
  2. On that page, click the JDK Download link. After the click, you will see the content page for JDK 1.8 installers as shown in the following image:
  1. Select Accept License Agreement by clicking its radio button.
  2. Start downloading the JDK depending on the operating system and architecture of your development machine. In the case of this book, we will be choosing the option jdk-8u112-windows-x64 since the operating system used by this book will be 64-bit.
  3. After saving the installer into the filesystem, run the installer and proceed with a series of installation wizards for JDK configuration with the inclusion of some JRE installation to your system.
  4. This is optional but it is recommended you create an environment variable JAVA_HOME for your newly installed JDK 1.8.112. On Windows operating systems:
    1. Open the System section of the Control Panel.
    2. Select the Advanced System Settings link. Windows 10 will prompt you with a User Account Control dialog box if you are not an administrator.
    3. Create a system variable JAVA_HOME and assign the location of the JDK directory to it.
    4. Look for the path system variable and append the following line: %JAVA_HOME\%bin.
  5. Verify if all classpath settings are created correctly. On Windows, open a new command terminal and run the javac -version command. This command must be recognized as a valid command; otherwise, check your configuration details again.

How it works...

The installed JDK will be the core language interpreter of Spring 5.0 projects, whether or not they are deployed to a Tomcat 9.x application server through Maven or Gradle. To read more about JDK 1.8, the reference http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html will provide you with some information about its highlights and will explain why it is popular nowadays in functional and reactive programming. More detailed concepts on functional programming will be discussed in Chapter 6, Functional Programming.

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:

Installing STS Eclipse 3.8 IDE

All the recipes will be implemented using Spring Tool Suite (STS) Eclipse 3.8 which has the latest features that support JDK 1.8.

Getting started

Visit the site https://spring.io/tools/sts/all and download the STS 3.8 release for Windows, Linux, or macOS. In our case, we will be opting for the Windows version. It is also available in 32-bit or 64-bit operating systems.

How to do it...

To get STS Eclipse 3.8, perform the following steps:

  1. After the download, unzip the file using WinZip or 7ZIP to your filesystem.
  1. Update its VM usage to enhance performance through making the heap grow to a larger amount by adding the -vmargs command to the eclipse.ini file inside the installation folder, or by appending to the Eclipse shortcut's target property. Following the command are the following Java heap memory configurations:
-Xms512m 
-Xmx1024m 
  1. Go to the installation folder <installation_folder>\sts-bundle\sts-3.8.3.RELEASE and run STS.exe.
  2. Running STS.exe will result in launching your workspace launcher. Create an Eclipse workspace as shown as follows:
  1. Then, you are now ready to create code snippets.

How it works...

STS Eclipse 3.8 is a customized all-in-one Eclipse-based distribution that provides support for Spring technologies such as Pivotal Cloud Foundry, Gradle, and Pivotal Server. Moreover, it is plugin-ready and contains language support, framework support, and runtime support for Java JDK 1.8 and Java EE 7.

The IDE has the following parts: views, perspectives, and the option menus. The view is the IDE's way of projecting its metadata or components graphically. Some views are console, debug, and task list, and data management views. The styling and the presence of the needed views depend on the type of perspective required for a particular project. A perspective is the logical arrangement of all these views. In our case, we have to choose a JEE perspective from the Window | Perspective | Open Perspective menu option to proceed with our programming.

But before we create our first project, always set the Java Runtime Environment to JDK's JRE. The JRE setting is located at Windows | Preferences and you need to Add... and choose the JDK's JRE as shown as follows:

You are now ready to create your Maven and Gradle project for our recipes in the next chapters.

Creating Eclipse projects using Maven

One option for creating our Spring 5.0 projects is through Maven. The STS Eclipse 3.8 has built-in Maven plugins that will create Maven-ready Eclipse projects easily.

Getting started

Before creating the first Maven project, check first the JRE workspace configuration of your IDE. As noted in the previous recipe, the JRE of your Eclipse must be set to the JDK's JRE. Moreover, check the embedded version of Maven installed in STS Eclipse 3.8 through the Windows | Preferences panel. STS 3.8 will be using its embedded Maven 3.0 for the deployment operations. The list of Maven versions is available at https://maven.apache.org/.

How to do it...

Follow the steps to create Maven Projects for our succeeding code snippets as follows:

  1. There are two ways that we can create a Maven project from scratch in STS. One option is to right-click the Project Explorer of the IDE in order to choose New | Other... from the pop-up window (or Ctrl-N). The other option is to click the File menu option then choose the New | Other... . Both of these operations will lead us to our New project wizard as shown as follows:
  1. On the menu wizard, click the Maven Module and then the Maven Project option. The New Maven project wizard will pop-up anew. Just click Create Simple Project (skip archetype selection) to create a clean project from scratch:
  1. Afterwards, the next wizard will require you to fill out the necessary Group Id and Artifact Id for your project. In the following example, the Group ID is org.packt.recipe.core and the Artifact Id is, let us say, ch01. The next important field that needs to be filled is Packaging and it must be set to war in our case:
  1. Click Finish. Look for the file pom.xml and insert below it the following lines to correct some Maven bugs:
<build> 
  <finalName>ch01-spring5-cookbook</finalName> 
  <plugins> 
    <plugin> 
      <artifactId>maven-war-plugin</artifactId> 
      <version>2.3</version> 
      <configuration> 
        <failOnMissingWebXml>false</failOnMissingWebXml> 
      </configuration> 
    </plugin> 
  </plugins> 
</build> 
  1. Finally, you must have the directory structure as follows in your own project explorer:

How it works...

Apache Maven is already a built-in plugin in Eclipse and helps developers manage projects and use some build tools to clean, install, and deploy Eclipse projects. It has the main configuration file which is called the Project Object Model (POM) file.

POM is the fundamental unit of work in Maven that contains information and configuration details about the project. Some core information in POM is <modelVersion>, which currently must be set to 4.0.0, <groupId>, that identifies the project uniquely together with <projectId> and <versionId> across all projects in the Maven repository, <artifactId>, which is the name of the WAR file without the version, and <packaging>, which is WAR.

Later in this book, we will be adding <properties> and <dependencies> and <plugins> for our Spring 5.0 code recipes in our pom.xml file.

Creating Spring STS Eclipse projects using Gradle

Another option in building Spring 5.0 projects is through the use of Gradle. STS Eclipse includes Gradle as one of its tooling and project management tools. In our case, we will be installing an STS Eclipse module extension in the easiest way in order to fully use Gradle.

Getting started

Install the Gradle module extension in our STS Eclipse 3.8 in order to clean, build, and deploy projects in Gradle. Perform the following steps:

  1. Click the Dashboard toolbar option of your Eclipse. After clicking, you will be opening the main dashboard of the IDE:
  1. On the dashboard, look for IDE EXTENSIONS and click that button. A new window showing all the available Eclipse STS extensions will pop up. Click on Gradle (STS Legacy) Support and install it:
  1. The next steps will just be similar to installing new Eclipse plugins. Just click the Install button and follow the installation wizard. Eclipse needs to be restarted after a successful installation.
  1. If you want to change the Gradle distribution, you can replace the Eclipse embedded Gradle installation with some new version at https://gradle.org/gradle-download/. Or you can shift to Eclipse Buildship with Gradle Plugin if some of the files are not supported by the installed Gradle plugin:

How to do it...

After installing the Gradle STS extension, perform the following steps to install the Spring Gradle project:

  1. After installing, you are ready to create a Gradle project for Spring development. Go to the New project wizard (Ctrl-N) of STS Eclipse and create a Gradle project.
  2. On the Gradle Project wizard, assign a name for your project and choose Java Quickstart for the Sample project option. Click Finish and it will take a while to create, build, clean, and install your Gradle STS project.
  3. Delete unnecessary project files. Right-click on the project and click on Gradle (STS) | Refresh all.
  1. Open the build.gradle and overwrite the existing configuration with this:
apply plugin: 'eclipse'
apply plugin: "war"

sourceCompatibility = 1.8
version = '1.0'

war {
baseName = 'ch02-gradle'
version = '1.0'
}

sourceCompatibility = 1.8

repositories {
mavenCentral()
jcenter()
}
  1. Right-click on the project and click Gradle (STS) | Tasks Quick Launcher to run the Gradle Task Launcher. Using the launcher, clean and build the project for the first time:
  1. Finally, at this point, you have created your Spring Gradle project which will look like this:

How it works...

The most important configuration file in a Gradle project is the build.gradle. First, we have to add apply plugin: 'java' to tell Gradle that Java is the core language in building the scripts, testing the codes, executing compiled objects, creating Javadoc, and deploying JAR or WAR files. Since all project management and tooling depends on STS Eclipse, there is a need to add apply plugin: 'eclipse' in order to tell Gradle that all descriptors are Eclipse-specific and can be integrated and executed with Eclipse core and extension plugins. A by-product of its project installation and execution are the Eclipse folders such as .project, and .classpath. And since this is a web development project, we need to apply plugin: 'war' to indicate that the deployment is at WAR mode. Later on we will be adding some plugins needed in the development of our recipes.

In the properties section, the configuration must tell Gradle the version of the JDK through the sourceCompatibility property. Another property is the version of the WAR or project deployment, which is at first set to 1.0. Since the mode of deployment is the web, Java must know the name and the version of the WAR file to be generated.

On the repositories section, the configuration must define where to find the dependencies, which are at JCenter and MavenCentral.

Deploying Spring projects using Maven

Our application server is Tomcat 9 and we will be using HTTP/2 to execute all Spring 5.0 projects at port 8443 with some certificates stored in the server's keystore.

Getting started

At this point, the Tomcat 9 server must be running at https://localhost:8843/ in all browsers. Using OpenSSL, certificates are already installed in JRE's keystore and our server's keystore. Moreover, you have already successfully created your STS Maven project in order for us to configure your POM file.

How to do it...

Open the POM file of your Maven project and add the following details:

  1. There is no available working Maven plugin for Tomcat 9 so we need to use the latest stable version, which is tomcat7-maven-plugin. Add the following Maven plugin details for Tomcat 7 deployment under the <plugins> section of the <build>:
<plugin> 
  <groupId>org.apache.tomcat.maven</groupId> 
  <artifactId>tomcat7-maven-plugin</artifactId> 
  <version>2.2</version> 
  <configuration> 
    <url>https://spring5server:8443/manager/text</url> 
    <path>/ch01</path> 
    <keystoreFile>C:MyFilesDevelopmentServersTomcat9.0 
    confspring5server.keystore</keystoreFile> 
    <keystorePass>packt@@</keystorePass> 
    <update>true</update> 
    <username>packt</username> 
    <password>packt</password> 
  </configuration> 
</plugin>
  1. Right-click on the project and click on Run As | Maven Build... and execute the following goal: clean install tomcat7:deploy
  1. Everything is successful if the console outputs this Maven log:

How it works...

The configuration detail starts with the <url> that sets Tomcat's plain-text-based administration interface used by Maven to invoke commands of the server. Maven needs to access the administration panel to allow the copy of the WAR file to the webapps. Since we will be using the TLS-enabled connector, we will be using the secured-HTTP together with the registered hostname in the keystore which is spring5server.

The tag <path> sets the context root of the project and must have a forward slash while the <username> and <password> refer to the credentials of the administrator having the roles manager-gui and manager-script.

The most important configuration details are <keystoreFile> and <keystorePass>. <keystoreFile> makes reference to the keystore of Tomcat that contains the TLS certificate. <keystorePass> provides the password used by <keystoreFile> in registering certificates. Together with these credentials, we have to be sure that the certificate has been added to the JRE's keystore which is <installation_folder>\Java1.8.112\jre\lib\security\cacerts.

<update> is required to undeploy all existing WAR files that already exist in the webapps. Sometimes the deployment does not work without this forced update.

Deploying Spring projects using Gradle

If the project is written in Gradle, there will be some modification to be done in our gradle.build configuration details.

Getting started

Validate that your Tomcat with TLS-enabled connection is working by running https://localhost:8080/ on any browser. Also, check if your STS Gradle project is clean and updated.

How to do it...

  1. Open the gradle.build file and add the buildScript() function that accepts a closure containing all libraries needed to be referenced in classpath. At this step, we need to import gradle-tomcat-plugin under the group com.bmuschko:
buildscript { 
    repositories { 
        jcenter() 
    } 
    dependencies { 
        classpath 'com.bmuschko:gradle-tomcat-plugin:2.0' 
    } 
} 
  1. Add the following libraries to the classpath:
apply plugin: 'com.bmuschko.tomcat' 
apply plugin: 'com.bmuschko.tomcat-base' 
  1. (Optional) Add the following Tomcat 9.0 libraries that enable Gradle to run embedded Tomcat through the tomcatRun() and tomatRunWar() functions:
dependencies { 
    def tomcatVersion = '9.0.0.M9' 
    tomcat "org.apache.tomcat.embed:tomcat-embed 
core:${tomcatVersion}", "org.apache.tomcat.embed:tomcat-embed-logging- juli:${tomcatVersion}" tomcat("org.apache.tomcat.embed:tomcat-embed- jasper:${tomcatVersion}") { exclude group: 'org.eclipse.jdt.core.compiler', module: 'ecj' }
}
  1. (Optional) Configure Tomcat 9 details through the tomcat() function:
tomcat { 
    httpsPort = 8443 
    enableSSL = true 
    users { 
        user { 
            username = 'packt' 
            password = 'packt' 
            roles = ['manager-gui', 'manager-script'] 
        } 
    } 
} 
  1. To deploy the project into the installed Tomcat 9, create a Gradle task deploy that copies the WAR file to the /webapp folder:
task deploy (dependsOn: war){ 
    copy { 
        from "build/libs" 
        into 
        "C:\MyFiles\Development\Servers\Tomcat9.0\webapps" 
        include "*.war" 
    } 
} 
  1. You can now run deploy in the Gradle Task Launcher.

How it works...

When it comes to building projects with conflicting versions of libraries, Gradle is one of those build tools that can satisfy any structure and state of project deployment and management. Since it is not written in XML, Gradle can provide logic in building classpath and project dependencies.

Gradle is efficient when it comes to incremental builds where the current and previous changes in deployment files are monitored. And when it comes to different repositories, Gradle can monitor changes of artifacts through effective repository-aware caches. In general, Gradle is advanced when it comes to repository management and project deployment than Maven.

Gradle is written in Groovy; thus, the build scripts are declarative, readable, and straightforward and can provide developers with easier conventions and philosophy of deployment.

First, Gradle must build the needed classpath libraries that are the main dependencies to the deployment, which happen to be com.bmuschko:gradle-tomcat-plugin:2.0. After building the external library, import the following plugins: com.bmuschko.tomcat and com.bmuschko.tomcat-base. Inject a closure to the tomcat() function that details all the needed configuration before the deployment. The custom Gradle task deploy takes all the configuration loaded by the tomcat() and war() functions. Running deploy in Gradle (STS) | Gradle Task Launcher will copy the WAR file found in build/libs to the Tomcat instance.

Installing the MySQL 5.7 database server

The book will be covering some concepts on how Spring 5.0 handles data persistence involving relational database management systems. MySQL 5.7 will be the database server that will be used to create, store, update, and delete records of data.

Getting started

How to do it...

  1. On the download page, choose the General Available (GA) Releases tab.
  2. Choose the desired platform through the Select Platform dropdown. The book will be using the MySQL server for Windows.
  3. Once the Windows platform is chosen, there are other options available for download under the Other Downloads link. Choose the Windows (x86, 32-bit) Windows MSI installer for easy installation.
  4. Afterwards, just click No thanks, just start my downloads! to download the installer immediately.
  5. After downloading the installer (for example, mysql-installer-community-5.7.17.0.msi), click the file and start the following wizards.
  6. Choose Developer Default as our server type.
  7. Install all the connectors.
  8. Use port 3306 and set the password to packt.
  9. After installing the MySQL server, proceed with installing the Samples and Examples scripts.
  10. After finishing the installation, create MySQL_HOME in your classpath and expose <installation_folder>MySQLMySQL Server 5.7bin commands.
  11. At this point, you are now ready to install the server for database transactions.

How it works...

To deal with SQL transactions, we can us the CLI of MySQL or the given GUI-based MySQL Workbench:

Installing the MongoDB 3.2 database server

Spring 5.0 has the capability to perform data transactions with NoSQL databases where schema design is not fixed and the data involved is so complex wherein its read-write operations are defined by graph theory. The MongoDB 3.2 server will highlight some NoSQL and document-based data transactions with Spring 5.0 using the raw implementation and its Spring Data module.

Getting started

How to do it...

  1. After downloading the installer (for example, mongodb-win32-x86_64-2008plus-ssl-3.2.0-signed.msi), follow the installation wizards:
  1. After the installation, create the MONGODB_HOME system variable in your classpath and expose the <installation_folder>MongoDbServer3.2bin commands.
  2. Since MongoDB requires a data directory to store all data, create a default data directory path, /data/db, at the root level (for example, C:datadb).
  3. You are now ready to start the MongoDb server.

How it works...

The MongoDB server will be running with the default port 27017. In order to run the server, we type the mongod command using the command-line terminal:

And then we open another terminal to open the server for the no-SQL transactions through the mongo command:

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Solve real-world problems using the latest features of the Spring framework like Reactive Streams and the Functional Web Framework.
  • Learn how to use dependency injection and aspect-oriented programming to write compartmentalized and testable code.
  • Understand when to choose between Spring MVC and Spring Web Reactive for your projects

Description

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.

Who is this book for?

Java developers who would like to gain in-depth knowledge of how to overcome problems that they face while developing great Spring applications. It will also cater to Spring enthusiasts, users and experts who need an arena for comparative analysis, new ideas and inquiries on some details regarding Spring 5.0 and its previous releases. A basic knowledge of Spring development is essential

What you will learn

  • • Understand how functional programming and concurrency in JDK 1.9 works, and how it will affect Spring 5.0
  • • Learn the importance and application of reactive programming in creating services, and also the process of creating asynchronous MVC applications
  • • Implement different Spring Data modules
  • • Integrate Spring Security to the container
  • • Create applications and deploy using Spring Boot
  • • Conceptualize the architecture behind Microservices and learn the details of its implementation
  • • Create different test cases for the components of Spring 5.0 components

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 27, 2017
Length: 670 pages
Edition : 1st
Language : English
ISBN-13 : 9781787128316
Vendor :
Pivotal
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Sep 27, 2017
Length: 670 pages
Edition : 1st
Language : English
ISBN-13 : 9781787128316
Vendor :
Pivotal
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 120.97
Spring 5 Design Patterns
€36.99
Spring 5.0 Cookbook
€41.99
Mastering Spring 5.0
€41.99
Total 120.97 Stars icon
Banner background image

Table of Contents

13 Chapters
Getting Started with Spring Chevron down icon Chevron up icon
Learning Dependency Injection (DI) Chevron down icon Chevron up icon
Implementing MVC Design Patterns Chevron down icon Chevron up icon
Securing Spring MVC Applications Chevron down icon Chevron up icon
Cross-Cutting the MVC Chevron down icon Chevron up icon
Functional Programming Chevron down icon Chevron up icon
Reactive Programming Chevron down icon Chevron up icon
Reactive Web Applications Chevron down icon Chevron up icon
Spring Boot 2.0 Chevron down icon Chevron up icon
The Microservices Chevron down icon Chevron up icon
Batch and Message-Driven Processes Chevron down icon Chevron up icon
Other Spring 5 Features Chevron down icon Chevron up icon
Testing Spring 5 Components Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5
(2 Ratings)
5 star 50%
4 star 0%
3 star 0%
2 star 50%
1 star 0%
Charles Baker Feb 23, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Excellent book, covering most new practices in Spring, very worth the $.
Amazon Verified review Amazon
OliverK Oct 31, 2017
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
Das Buch lebt vom Beispiel-Code, der ist schwarz-weiß gedruckt (kein Syntax-Highlighting) und durch viele ungeschickte Zeilenumbrüche oft nur mühsam zu erfassen. Der Code der zahlreichen Rezepte baut in weiten Teilen aufeinander auf; aus dem Code-Ausschnitt eines Rezepts ist das Gesamtbild nur schwer abzuleiten. Hier ist die Arbeit mit dem separat erhältlichen Code erforderlich, auf den im Buch an vielen Code-Stellen verwiesen wird. In den begleitenden Erklärungen der Rezepte finde ich überdurchschnittlich viele Fehler: fehlende/falsche Bilder und irrweisende Referenzen.All diese Aspekte sah ich in vielen anderen Werken qualitativ hochwertiger gelöst. Insgesamt bleibt bei mir ein unbefriedigender Eindruck zurück. Ich werde zu diesem Thema weitere Literatur kaufen (müssen) und werde diese von einem anderen Verlag wählen.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.