Spring 5.0 Cookbook - Sherwin John Calleja Tragura - E-Book

Spring 5.0 Cookbook E-Book

Sherwin John Calleja Tragura

0,0
45,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Over 100 hands-on recipes to build web applications easily and efficiently IN Spring 5.0

About This Book

  • 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

Who This Book Is 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

In Detail

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.

Style and Approach

This book follows a cookbook style approach, presenting a problem and showing you how to overcome it with useful recipes. The examples provided will help you code along as you learn.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 616

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Spring 5.0 Cookbook

 

 

 

 

 

 

 

 

 

Recipes to build, test, and run Spring applications efficiently

 

 

 

 

 

 

 

 

 

 

 

 

Sherwin John Calleja Tragura

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Spring 5.0 Cookbook

 

Copyright © 2017 Packt Publishing

 

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

 

First published: September 2017

 

Production reference: 1250917

 

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

 

ISBN 978-1-78712-831-6

www.packtpub.com

Credits

Author

Sherwin John Calleja Tragura

Copy Editor

Safis Editing

Reviewer

Glenn Base De Paula

Project Coordinator

Vaidehi Sawant

Commissioning Editor

Aaron Lazar

Proofreader

Safis Editing

Acquisition Editor

Sandeep Mishra

Indexer

Francy Puthiry

Content Development Editor

Zeeyan Pinheiro

Graphics

Abhinash Sahu

Technical Editor

Ketan Kamble

Production Coordinator

Nilesh Mohite

 

About the Author

Sherwin John Calleja Tragura started his career as a student assistant and a mathematics tutor during his college years at the University of the Philippines Los Baños, Laguna, Philippines. With meager resources, he graduated as a Department of Science and Technology (DOST) R.A. 7687 scholar under the Bachelor Of Computer Science degree. Immediately after graduation, he took up the offer to teach CMSC 150 (numerical and symbolic computation) at the Institute of Computer Science and completed his master's degree in computer science simultaneously. He became part of the International Rice Research Institute (IRRI) software team, which gave him the opportunity to use Struts, Spring, and RCP frameworks in many of its software projects.

Based on his experience at IRRI, he was given an opportunity to work as a Java analyst in various companies in Manila, such as ABSI, PHILAM- AIG, and Ayala Systems and Technology Inc. (ASTI). These companies have strengthened his skill set through training in Java and Java Enterprise platforms and some popular tools such as EMC Documentum, Alfresco Document, and Records Management System. He got his first career certification in the EMC Documentum Proven Associate course (E20-120).

After a few years, he decided to become an independent consultant and trainer, providing services mostly forJava-based projects, Alfresco, and Apache OFBiz requirements. He started his venture as a Java-JEE Bootcamp with 77Global and is currently a trainer at Software Laboratory Inc. (SLI), Alibata Business and Technology Services Inc. and Nityo Infotech, Philippines. He also conducts training and talks around the Philippines, for instance, in Cebu City and Tacloban City.

Sherwin has contributed as a technical reviewer to various books by Packt Publishing, including Delphi Cookbook, Alfresco 3 Records Management, Alfresco Share, and Mastering Hibernate. He owes everything to Packt Publishing with the unforgettable experience in the technical reviewing tasks, which have been an essential part of his career.

As an Oracle Certified Associate and Java SE 7 Programmer (1Z0-803), Sherwin will continue his mandate as a technical trainer, developer, architect, and designer to help the industry improve its standards in information technology. He will always be an epitome of honor, excellence, and service when it comes to software development and business intelligence.

About the Reviewer

Glenn De Paula is a product of the University of the Philippines Integrated School and is a computer science graduate of the country’s most prestigious University of the Philippines. He has 12 years of industry experience, most of which he got working for the government’s ICT institute and recently in the banking industry.

He uses Spring, Grails, and Javascript for his day-to-day activities. He has developed numerous Java web applications for the government and has also been the technical team lead for several projects. He currently manages Java developers assigned to different projects in one of the country’s most reputable banks.

He is consistently involved in systems analysis and design, source code review, testing, implementation, training, and mentoring. He is currently learning NodeJS and Blockchain technologies in his free time.

 

I would like to thank the author of this book, the editors, and Packt Publishing for giving me the opportunity to review this great informative book. I would also like to thank my managers and supervisors for mentoring me and trusting me with projects that helped improve my career. Thank you very much to my family and friends for all their support. Especially, I thank my wife, Elaine, for all the love and patience.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by Packt

Copy and paste, print, and bookmark content

On demand and accessible via a web browser

 

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review.

If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

Table of Contents

Preface

What this book covers

What you need for this book

Who this book is for

Sections

Getting ready

How to do it…

How it works…

There's more…

See also

Conventions

Reader feedback

Downloading the example code

Downloading the color images of this book

Errata

Piracy

Questions

Getting Started with Spring

Installing Java Development Kit 1.8

Getting started

How to do it...

How it works...

Installing Tomcat 9 and configuring HTTP/2

Getting started

How to do it...

How it works...

Installing STS Eclipse 3.8 IDE

Getting started

How to do it...

How it works...

Creating Eclipse projects using Maven

Getting started

How to do it...

How it works...

Creating Spring STS Eclipse projects using Gradle

Getting started

How to do it...

How it works...

Deploying Spring projects using Maven

Getting started

How to do it...

How it works...

Deploying Spring projects using Gradle

Getting started

How to do it...

How it works...

Installing the MySQL 5.7 database server

Getting started

How to do it...

How it works...

Installing the MongoDB 3.2 database server

Getting started

How to do it...

How it works...

Learning Dependency Injection (DI)

Implementing a Spring container using XML

Getting started

How to do it...

How it works...

Implementing a Spring container using JavaConfig

Getting started

How to do it...

How it works...

Managing beans in an XML-based container

Getting started

How to do it...

How it works...

Managing beans in the JavaConfig container

Getting started

How to do it...

How it works...

Creating Singleton and Prototype beans

Getting started

How to do it...

How it works...

Defining eager and lazy spring beans

Getting started

How to do it...

How it works...

Creating an inner bean

Getting started

How to do it...

How it works...

Injecting Collections and Properties

Getting started

How to do it...

How it works...

Creating a Spring MVC using an XML-based approach

Getting started

How to do it...

How it works...

Creating a Spring MVC using the JavaConfig approach

Getting started

How to do it...

How it works...

Generating multiple ApplicationContexts

Getting started

How to do it...

How it works...

Using ResourceBundleMessageSource for Views

Getting started

How to do it...

How it works...

Implementing MVC Design Patterns

Creating the simple @Controller

Getting started

How to do it...

How it works...

Creating a simple @Controller with method-level URL mapping

Getting started

How to do it...

How it works...

Designing a simple form @Controller

Getting started

How to do it...

How it works...

Creating a multi-action @Controller

Getting started

How to do it...

How it works...

Form validation and parameter type conversion

Getting started

How to do it...

How it works...

Creating request- and session-scoped beans

Getting started

How to do it...

How it works...

Implementing page redirection and Flash-scoped beans

Getting started

How to do it...

How it works...

Creating database connection pooling

Getting started

How to do it...

How it works...

Implementing the DAO layer using the Spring JDBC Framework

Getting Started

How to do it...

How it works...

Creating a service layer in an MVC application

Getting started

How to do it...

How it works...

Securing Spring MVC Applications

Configuring Spring Security 4.2.2

Getting started

How to do it...

How it works...

Mapping sessions to channels and ports

Getting started

How to do it...

How it works...

Customizing the authentication process

Getting started

How to do it...

How it works...

Implementing authentication filters, login success, and failure handlers

Getting started

How to do it...

How it works...

Creating user details

Getting started

How to do it...

How it works...

Generating encrypted passwords

Getting started

How to do it...

How it works...

Applying Security to MVC methods

Getting started

How to do it...

How it works...

Creating roles and permissions from the database

Getting started

How to do it...

How it works...

Managing and storing sessions

Getting started

How to do it...

How it works...

Solving Cross-Site Request Forgery (CSRF) and session fixation attacks

Getting started

How to do it...

How it works...

Solving Cross-Site Scripting (XSS) and clickjacking attacks

Getting started

How to do it...

How it works...

Creating interceptors for login data validation

Getting started

How to do it...

How it works...

Cross-Cutting the MVC

Logging and auditing service methods

Getting started

How to do it...

How it works...

Managing DAO transactions

Getting started

How to do it...

How it works...

Monitoring services and request handlers

Getting started

How to do it...

How it works...

Validating parameters and arguments

Getting started

How to do it...

How it works...

Managing exceptions

Getting started

How to do it...

How it works...

Implementing the caching mechanism

Getting started

How to do it...

How it works...

Intercepting request transactions

Getting started

How to do it...

How it works...

Implementing user authentication

Getting started

How to do it...

How it works...

Accessing with restrictions

Getting started

How to do it...

How it works...

Controlling concurrent user access

Getting started

How to do it...

How it works...

Implementing a mini-workflow using AOP

Getting started

How to do it...

How it works...

Functional Programming

Implementing lambda expressions using anonymous inner classes

Getting started

How to do it...

How it works...

Implementing lambda expression using @FunctionInterface

Getting started

How to do it...

How it works...

Applying the built-in functional interfaces

Getting started

How to do it...

How it works...

Applying method and constructor references

Getting started

How to do it...

How it works...

Using the Stream API

Getting started

How to do it...

How it works...

Applying streams to collections

Getting started

How to do it...

How it works...

Applying streams to NIO 2.0

Getting started

How to do it...

How it works...

Using parallel streams

Getting started

How to do it...

How it works...

Reactive Programming

Applying the observer design pattern using Reactive Streams

Getting started

How to do it...

How it works...

Creating Mono<T> and Flux<T> publishers

Getting started

How to do it...

How it works...

Implementing the Subscriber<T> interface

Getting ready

How to do it...

How it works...

Applying backpressure to Mono<T> and Flux<T>

Getting ready

How to do it...

How it works...

Managing task executions using Schedulers

Getting ready

How to do it...

How it works...

Creating concurrent and parallel emissions

Getting ready

How to do it...

How it works...

Managing continuous data emission

Getting ready

How to do it...

How it works...

Implementing Stream manipulation and transformation

Getting ready

How to do it...

How it works...

Testing Reactive data transactions

Getting ready

How to do it...

How it works...

Implementing Reactive events using RxJava 2.x

Getting ready

How to do it...

How it works...

Reactive Web Applications

Configuring the TaskExecutor

Getting started

How to do it...

How it works...

SimpleAsyncTaskExecutor

ThreadPoolTaskExecutor

ConcurrentTaskExecutor

Implementing @Async services

Getting started

How to do it...

How it works...

Creating asynchronous controllers

Getting started

How to do it...

How it works...

Creating @Scheduled services

Getting started

How to do it...

How it works...

Using Future<T> and CallableFuture<T>

Getting started

How to do it...

How it works...

Using Mono<T> and Flux<T> publishers for services

Getting started

How to do it...

How it works...

Creating Mono<T> and Flux<T> HTTP response

Getting started

How to do it...

How it works...

Integrating RxJava 2.0

Getting started

How to do it...

How it works...

Using FreeMarker to render Publisher<T> stream

Getting started

How to do it...

How it works...

Using Thymeleaf to render a Publisher<T> stream

Getting started

How to do it...

How it works...

Applying security on TaskExecutors

Getting started

How to do it...

How it works...

Spring Boot 2.0

Building a non-reactive Spring MVC application

Getting started

How to do it...

How it works...

Configuring Logging

Getting started

How to do it...

How it works...

Adding JDBC Connectivity

Getting started

How to do it...

How it works...

Building a reactive Spring MVC application

Getting started

How to do it...

How it works...

Configuring Spring Security 5.x

Getting started

How to do it...

How it works...

Using reactive view resolvers

Getting started

How to do it...

How it works...

Using RouterFunction and HandlerFunction

Getting started

How to do it...

How it works...

Implementing Spring Data with JPA

Getting started

How to do it...

How it works...

Implementing REST services using @RestController and Spring REST

Getting started

How to do it...

How it works...

Applying Spring Cache

Getting started

How to do it...

How it works...

The Microservices

Exposing RESTful services in Spring 5

Getting started

How to do it...

How it works...

Using the actuator REST endpoints

Getting started

How to do it...

How it works...

Building a client-side application with RestTemplate, AsyncRestTemplate and, WebClient

Getting started

How to do it...

How it works...

Configuring the Eureka server for service registration

Getting started

How to do it...

How it works...

Implementing the Eureka service discovery and client-side load balancing

Getting started

How to do it...

How it works...

Applying resiliency to client applications

Getting started

How to do it...

How it works...

Consuming endpoints using a declarative method

Getting started

How to do it...

How it works...

Using Docker for deployment

Getting started

How to do it...

How it works...

Batch and Message-Driven Processes

Building synchronous batch processes

Getting started

How to do it...

How it works...

Implementing batch processes with a database

Getting started

How to do it...

How it works...

Constructing asynchronous batch processes

Getting started

How to do it...

How it works...

Building synchronous interprocess communication using AMQP

Getting started

How to do it...

How it works...

Creating asynchronous send-receive communication

Getting started

How to do it...

How it works...

Creating an event-driven asynchronous communication using AMQP

Getting started

How to do it...

How it works...

Creating stream communication with Spring Cloud Stream

Getting started

How to do it...

How it works...

Implementing batch processes using Spring Cloud Task

Getting started

How to do it...

How it works...

Other Spring 5 Features

Using Hibernate 5 object-relational mapping

Getting ready

How to do it...

How it works...

Applying Hazelcast distributed caching

Getting ready

How to do it...

How it works...

Building client-server communications with WebSocket

Getting ready

How to do it...

How it works...

Implementing Reactive WebSocket communication

Getting ready

How to do it...

How it works...

Implementing asynchronous Spring Data JPA properties

Getting ready

How to do it...

How it works...

Implementing Reactive Spring Data JPA repositories

Getting ready

How to do it...

How it works...

Using Spring Data MongoDB

Getting ready

How to do it...

How it works...

Building applications for big data storage

Getting ready

How to do it...

How it works...

Building a Spring 5 application using Kotlin

Getting ready

How to do it...

How it works...

Testing Spring 5 Components

Creating tests for Spring MVC components

Getting ready

How to do it...

How it works...

Building standalone controller tests

Getting ready

How to do it...

How it works...

Creating tests for DAO and service layers

Getting ready

How to do it...

How it works...

Creating tests on secured applications

Getting ready

How to do it...

How it works...

Creating tests using Spring Boot 2.0

Getting ready

How to do it...

How it works...

Creating tests for Spring Data JPA

Getting ready

How to do it...

How it works...

Building tests for blocking, asynchronous and reactive RESTful services

Getting ready

How to do it...

How it works...

Building tests for Kotlin components

Getting ready

How to do it...

How it works...

Preface

A cookbook is a definitive reference material that consists of several essential recipes on computer programming used for academic, professional, or personal workshops. This book is a large reference database of programming concepts, which aims to describe, highlight, and identify the general features of Spring Framework 5 and also its distinctive features and characteristics as the newest installment of Spring platforms.

The book is written for users who wants to build Spring 5 applications using its core Maven dependencies and for those who prefer to use Spring Boot as the mechanism for web development. It is divided into disciplines that are considered strengths of Spring 5 in which some are familiar concepts such as bean scopes, Model-View-Controller, aspect-object programming, @Async transactions, and Spring security concepts. There are also new theoretical frameworks that can only be found in this Spring version such as Reactor Core, WebFlux, cold and hot streams, and reactive web programming.

You will be guided on how to install the appropriate tools and plug-ins for Spring 5 to work properly. For those who are new to Spring framework, you will also be given a short discussion on its core principles through recipes that handle Dependency Injection and Inversion of Control and implementation of the ApplicationContext container. For experts, this book offers some recipes that illustrate how to implement reactive components such as reactive JPA, service layers, message-driven transactions, and WebSocket implementation.

When it comes to difficulty levels, there are parts that are for beginners and enthusiasts who want to learn Spring web development. But most chapters are intended for experienced Spring users who want to learn functional and reactive programming components of this newest Spring installment. This will provide a new paradigm to those who are seeking optimal and faster software performance with the help of the Stream API, Publisher<T>, Flux<T>, @Async, Callable<T>, and HandlerFunction<T>. These are just few concepts that this book will emphasize and expound through some robust and practical set of recipes.

What this book covers

Chapter 1, Getting Started with Spring, is the installation and configuration section of the book. It consists of recipes that enumerate the steps on how to install Java 1.8, Tomcat 9 with TLS, Eclipse STS 8.3, MySQL 5.7, and MongoDB 3.2. This will also provide a procedure on how to build a Maven project with Spring 5 dependencies and deploy it using the Tomcat Maven plugin.

Chapter 2, Learning Dependency Injection (DI), covers the core concepts of Inversion of Control (IoC) design pattern. This chapter provides recipes on how to build ApplicationContext through XML-based configurations and the JavaConfig specification. You will also be guided on how to perform a @Bean injection and autowiring. Most importantly, this chapter will highlight the role of IoC in building Spring MVC web applications.

Chapter 3, Implementing MVC Design Pattern, highlights the construction of Spring 5 web applications based on its Spring WebMvc module. This will provide recipes that aim to implement the controller, service, and DAO layers with some supporting features such as view resolvers, message bundles, and JDBC connectivity.

Chapter 4, Securing Spring MVC Application, is all about Spring Security integration with Spring 5. The chapters that use Spring MVC will be applying Spring Security 4, while those that implement th Spring WebFlux module will be using Spring Security 5 with asynchronous and reactive transactions. Advance topics such as protection against Cross-Site Request Forgery (CSRF), session fixation, and cross-site scripting (XSS) and Clickjacking will also be covered in some recipes.

Chapter 5, Cross-Cutting the MVC, contains recipes that discuss implement aspects, advices, and pointcuts. The aspect-object programming paradigm will be thoroughly discussed, focusing on how it will be used across the Spring 5 platform. Concepts such as improvised security, validating method parameters, monitoring @Controller request transactions, and interception will also be included in the recipes.

Chapter 6, Functional Programming, contains recipes that will layout the foundation of functional programming paradigm in Spring 5. This will showcase the Stream API of Java 1.8 and its threaded operations being applied to the service layer of the platform. Topics such as sequential and parallel streams will be covered here.

Chapter 7, Reactive Programming, focuses on Spring 5 integration with the Reactor Core module. The recipes of this chapter will apply Publisher<T> and Subscriber<T> from the reactive stream specification in order to generate reactive data streams with short-lived and continuous stream flows. Also included are implementations of asynchronous transactions using @Async, Callable<T>, and DeferredResult<T>. Apart from Reactor Core, this chapter will also include other reactive libraries such as RxJava 2.0 used in building the reactive service layer of Spring 5.

Chapter 8, Reactive Web Applications, is where we start using Reactor Core in building reactive web applications. This includes recipes that use Publisher<T>, Flux<T>, and Mono<T> in building the service and the @Controller layer. Some recipes also discuss how to implement Callable<T> and DeferredResult<T> response transactions. In this chapter, some view resolvers will be introduced to recognize reactive streams.

Chapter 9, Spring Boot 2.0, discusses how to build and deploy Spring MVC and Spring WebFlux projects using Spring Boot 2.0. It is only in this chapter that the functional and reactive web framework of Spring 5 will be completely implemented using the HandlerFunction<T> and RouterFunction<T> reactive components executed by the Reactor Netty server.

Chapter 10, The Microservices, applies the concept of functional and reactive web framework to microservices. This provides a set of recipes that will showcase the strength of Spring Boot 2.0 in building and consuming synchronous, asynchronous, and reactive services in a microservice. In the chapter, we will cover the procedure to implement a loosely-coupled microservices setup through the Eureka server or Docker.

Chapter 11, Batch and Message-Driven Processes, talks about how to implement a totally loosely-coupled microservices through message-driven transactions. There are also recipes that will discuss on how to implement background batch processes using Spring Batch and Spring Cloud Task.

Chapter 12, Other Spring 5 Features, is one of the most important chapters in this book because it showcases other reactive and non-reactive components of Spring 5 that are not mentioned in the previous chapter but are useful to professionals. In this chapter, there are recipes dedicated to how to enable Hibernate 5, WebSocket, and HazelCast caching. Also, there are others written to showcase the reactive features of Spring 5 such as Spring Data JPA, Spring Data MongoDB, and Kotlin.

Chapter 13, Testing Spring 5 Components, highlights the Spring TestContext framework and how it is utilized in testing synchronous, asynchronous, and reactive Spring components such as native and REST services, repositories, JPA transactions, controllers, and views.

What you need for this book

Firstly, this book is intended for readers who have a background at least in Java SDK programming. This book does not cover anything about how to start dealing with Java as a language. Secondly, each chapter contains recipes that can be developed using STS Eclipse 3.8 and can be executed using Apache Tomcat 9.x and the Reactor Netty server. The following are the required tools and libraries needed to perform the recipes in this book:

Any machine with at least 4 GB of RAM

Java 1.8

STS Eclipse 3.8

Apache Tomcat 9.x

OpenSSL for Windows

MySQL 5.7

MongoDB 3.2

RabbitMQ 3.6

Erlang 9.0

Apache Couchdb 2.1.0

Docker Toolbox for Windows

Google Chrome or Mozilla Firefox browser

Other versions of these requirements will not be covered in this book.

Who this book is for

This book is composed of two menus: core concepts and advance concepts. The core concepts found in the recipes of chapters 1 to 3 are recommended to Java programmers who have no background in Spring Framework but are willing to start their career with the Spring 5 platform. Also, enthusiasts who know OOP and MVC concepts can also deal with the first three chapters since these are just the same ideas and principles being implemented in Spring 4 and below.

The recipes covered in chapters 4 to 13 are for experienced Spring developers who want to learn how to integrate modules such as Spring Security, Spring WebFlux, Reactor Core, Spring Batch, Spring Cloud, and advance related libraries. Aspects, advices, pointcuts, and interceptors, for instance, can only be understood by readers who know where in the Spring platform to apply the cross-cutting procedure. It also takes a deep knowledge of Spring when it comes to implementing REST web services and how to consume them using client APIs. Since this book is more inclined to asynchronous and reactive programming concepts, this book will be challenging for someone who knows Spring Framework very well.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).

To give clear instructions on how to complete a recipe, we use these sections as follows:

Getting ready

This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.

Hover the mouse pointer on the

SUPPORT

tab at the top.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box.

Select the book for which you're looking to download the code files.

Choose from the drop-down menu where you purchased this book from.

Click on

Code Download

.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for Windows

Zipeg / iZip / UnRarX for Mac

7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Spring-5.0-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from http://www.packtpub.com/sites/default/files/downloads/Spring5Cookbook.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at [email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

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

All Java JDK installers are downloaded from Oracle's site at http://www.oracle.com/technetwork/java/javase/downloads/index.html.

How to do it...

To download JDK 1.8, perform the following steps:

Visit the preceding Oracle's page for downloads.

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:

Select

Accept License Agreement

by clicking its radio button.

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.

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.

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:

Open the

System

section of the

Control Panel

.

Select the

Advanced System Settings

link. Windows 10 will prompt you with a

User Account Control

dialog box if you are not an administrator.

Create a system variable

JAVA_HOME

and assign the location of the JDK directory to it.

Look for the path system variable and append the following line:

%JAVA_HOME\%bin

.

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

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:

Check if you have installed JDK 1.8 in your system. Tomcat 9 only runs with the latest JDK 1.8 without error logs.

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:

You can retain the default server startup port (

8005

), HTTP connector port (

8080

), and AJP port (

8009

) or configure according to your own settings.

Provide the

manager-gui

with the username as

packt

and its password as

packt

.

After the installation process, start the server and check whether the main page is loaded using the URL

http://localhost:8080/

.

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

.

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.

Create an environment variable

OPENSSL_HOME

for your operating system. Register it into the

$PATH

the

%OPENSSL_HOME%/bin

.

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

.

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

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]

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

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.

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

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.

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

).

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>

Save the

server.xml

.

Open

C:\Windows\System32\drivers\etc\hosts

file and add the following line at the end:

127.0.0.1 spring5server

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:

You will now be running HTTP/2.

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:

After the download, unzip the file using WinZip or 7ZIP to your filesystem.

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

Go to the installation folder

<installation_folder>\sts-bundle\sts-3.8.3.RELEASE

and run

STS.exe

.

Running

STS.exe

will result in launching your workspace launcher. Create an Eclipse workspace as shown as follows:

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:

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:

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:

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:

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>

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:

Click the

Dashboard

toolbar option of your Eclipse. After clicking, you will be opening the main dashboard of the IDE:

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:

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.

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

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>

Right-click on the project and click on

Run As

|

Maven Build...

and execute the following goal:

clean install tomcat7:deploy

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>