Zachary Palmer

Zachary Palmer


Reactive Programming in Java: Using the WebClient Class

Originally published at

In this article, we will talk about the WebClient class found in the Spring Boot framework. You can access the source code for this article here

This class would be the equivalent of the RestTemplate class, but it works with asynchronous requests.

If you want to use this class, you should put these dependencies in your Maven file.


This is also why you need to use WebFlux, which is available in version 5 of Spring. Remember that this version of Spring requires Java 8 or higher.

With WebFlux, which is based on Project Reactor, you can write reactive applications. This kind of application is characterized because the requests aren't blocking and functional programming is widely used.

If you want to understand this article, you need basic prior knowledge about the Reactor and the Mono class. Although, if you have used Streams in Java, you may think that a Mono object is like a Stream that can emit a value or an error.

But I am not going to delve into these issues because they are beyond the scope of this article. It would be sufficient to say that when using the WebClient class, you can make several calls in parallel, so if each request is answered in 2 seconds and you make 5 calls, you can get all the answers in just over 2 seconds, instead of 10.

Parallel Request

In this example project, I have written a server and a client. The server will be running in the 8081 port, and the client will listen in the 8080 port.

This is the code that executes the server application.

public class WebServerApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(WebServerApplication.class).
properties(Collections.singletonMap("server.port", "8081")).run(args);

If you make a request to http://localhost:8080/client/XXX, the function testGet will be executed.

public class ClientController {
final String urlServer="http://localhost:8081";
public Mono<ResponseEntity<Mono<String>>> testGet(@PathVariable String param) {
final long dateStarted = System.currentTimeMillis();
WebClient webClient = WebClient.create(urlServer+"/server/");
Mono<ClientResponse> respuesta = webClient.get().uri("?queryParam={name}", param).exchange();
Mono<ClientResponse> respuesta1 = webClient.get().uri("?queryParam={name}","SPEED".equals(param)?"SPEED":"STOP").exchange();
Mono<ResponseEntity<Mono<String>>> f1 =, respuesta1)
.map(t -> {
if (!t.getT1().statusCode().is2xxSuccessful()) {
return ResponseEntity.status(t.getT1().statusCode()).body(t.getT1().bodyToMono(String.class));
if (!t.getT2().statusCode().is2xxSuccessful()) {
return ResponseEntity.status(t.getT2().statusCode()).body(t.getT2().bodyToMono(String.class));
return ResponseEntity.ok().body(Mono.just(
"All OK. Seconds elapsed: " + (((double) (System.currentTimeMillis() - dateStarted) / 1000))));
return f1;

This is a simple controller that performs two requests to the URL http://localhost:8081. In the first request, the parameter passed is the function received in the param variable. In the second, the sentence "STOP" is sent if the param variable is different from the word SPEED.

The server upon receiving the parameter "STOP" will wait 5 seconds and then will answer.

From the moment we create the instance of the class WebClient, I specify the URL of the request.

WebClient webClient = WebClient.create(urlServer+"/server/");

Then, it executes the call of the type GET to the server passing the parameter QueryParam. In the end, when executing the function exchange, it will receive a Mono object containing a ClientResponse class that is equivalent to the ResponseEntity object of the RestTemplate class. The class ClientResponse will have the HTTP code, the body, and the headers sent by the server.

Mono<ClientResponse> respuesta = webClient.get().uri("?queryParam={name}", param).exchange();

Wait a minute...

Did I say it will execute? Well, I lied. Really only what I want to do has been declared. In reactive programming, until someone does not subscribe to a request, nothing is executed, so the request to the server has not yet been made.

On the next line, the second request to the server is defined.

Mono<ClientResponse> respuesta1 = webClient.get()

Finally, a Mono object is created, which will be the result of the previous two, using the zip function.

Using the map function, a ResponseEntity object with the HTTP code equal to OK will be returned if the two requests have answered a 2XX code; otherwise, the code and answer of the server will be returned.

Being WebClient-reactive, the two requests are realized simultaneously, and therefore, you will be able to see that if you execute this code: curl http://localhost:8080/client/STOP, you have the answer in just over 5 seconds, even if the sum of the call time is greater than 10 seconds.

All OK. Seconds elapsed: 5.092

A POST request

In the testURLs function, there is an example of a call using POST.

This function receives a Map in the body that will then be placed in the request headers. In addition, this map will be sent in the body of the request that will be made to the server.

public Mono<String> testURLs(@RequestBody Map<String,String> body,
@RequestParam(required = false) String url) {
log.debug("Client: in testURLs");
WebClient.Builder builder = WebClient.builder().baseUrl(urlServer).
if (body!=null && body.size()>0 )
for (Map.Entry<String, String> map : body.entrySet() )
builder.defaultHeader(map.getKey(), map.getValue());
WebClient webClient =;
String urlFinal;
if (url==null)
Mono<String> respuesta1 =
.flatMap( x -> 
if ( ! x.statusCode().is2xxSuccessful())
return Mono.just("LLamada a "+urlServer+urlFinal+" Error 4xx: "+x.statusCode()+"\n");
return x.bodyToMono(String.class);
return respuesta1;

To insert the body of the message, the auxiliary class BodyInserters will be used. If the message were on the object Mono, this code could be used:


When performing a flatMap, the output of the ClientResponse object will be captured and a Mono object will be returned with the string to be returned.

The flatMap function will flatten that Mono object and extract the string inside it, and that is why a Mono <String> will be received and not a Mono <Mono <String>>. However, it would happen if we used the function map.

Making the following call:

curl  -s -XPOST http://localhost:8080/client  -H 'Content-Type: application/json' -d'{"aa": "bbd"}'

The following output will be obtained:

the server said: {aa=bbd}
Headers: content-length:12
Headers: aa:bbd
Headers: accept-encoding:gzip
Headers: Content-Type:application/json
Headers: accept:*/*
Headers: user-agent:ReactorNetty/0.9.0.M3
Headers: host:localhost:8081

This output is produced by the function postExamle of the server

public ResponseEntity<String> postExample(@RequestBody Map<String,String> body,ServerHttpRequest  request) {
String s="the server said: "+body+"\n";
for (Entry<String, List<String>> map : request.getHeaders().entrySet())
s+="Headers: "+map.getKey()+ ":"+map.getValue().get(0)+"\n";
return ResponseEntity.ok().body(s);

Note that when using the WebFlux library that is not fully compatible with javax.servlet, we must receive a ServerHttpRequest object to collect all raw headers. The equivalent in a non-reactive application would be an HttpServletRequest object.

If you execute the sentence:

curl  -s -XPOST http://localhost:8080/client?url=aa  -H 'Content-Type: application/json' -d'{"aa": "bbd"}'

The client will try to call http://localhost:8081/server/aa, which will cause an error, and the following will be received.

http://localhost:8081/server/aa Called. Error 4xx: 404 NOT_FOUND

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

Java Programming Masterclass for Software Developers

Selenium WebDriver with Java -Basics to Advanced+Frameworks

Java In-Depth: Become a Complete Java Engineer!

Top 4 Spring Annotations for Java Developer in 2019

Java Tutorial for Absolute Beginners

100+ Java Interview Questions and Answers In 2019

Python vs Java: Understand Object Oriented Programming

Angular 7 + Spring Boot CRUD Example

#java #web-service #spring-boot

What is GEEK

Buddha Community

Reactive Programming in Java: Using the WebClient Class
Tyrique  Littel

Tyrique Littel


How to Install OpenJDK 11 on CentOS 8

What is OpenJDK?

OpenJDk or Open Java Development Kit is a free, open-source framework of the Java Platform, Standard Edition (or Java SE). It contains the virtual machine, the Java Class Library, and the Java compiler. The difference between the Oracle OpenJDK and Oracle JDK is that OpenJDK is a source code reference point for the open-source model. Simultaneously, the Oracle JDK is a continuation or advanced model of the OpenJDK, which is not open source and requires a license to use.

In this article, we will be installing OpenJDK on Centos 8.

#tutorials #alternatives #centos #centos 8 #configuration #dnf #frameworks #java #java development kit #java ee #java environment variables #java framework #java jdk #java jre #java platform #java sdk #java se #jdk #jre #open java development kit #open source #openjdk #openjdk 11 #openjdk 8 #openjdk runtime environment

Lawrence  Lesch

Lawrence Lesch


Superdom: Better and Simpler ES6 DOM Manipulation


You have dom. It has all the DOM virtually within it. Use that power:

// Fetch all the page links
let links = dom.a.href;

// Links open in a new tab = '_blank';

Only for modern browsers

Getting started

Simply use the CDN via

<script src=""></script>

Or use npm or bower:

npm|bower install superdom --save


It always returns an array with the matched elements. Get all the elements that match the selector:

// Simple element selector into an array
let allLinks = dom.a;

// Loop straight on the selection
dom.a.forEach(link => { ... });

// Combined selector
let importantLinks = dom['a.important'];

There are also some predetermined elements, such as id, class and attr:

// Select HTML Elements by id:
let main =;

// by class:
let buttons = dom.class.button;

// or by attribute:
let targeted =;
let targeted = dom.attr['target="_blank"'];


Use it as a function or a tagged template literal to generate DOM fragments:

// Not a typo; tagged template literals
let link = dom`<a href="">Google</a>`;

// It is the same as
let link = dom('<a href="">Google</a>');

Delete elements

Delete a piece of the DOM

// Delete all of the elements with the class .google
delete;   // Is this an ad-block rule?


You can easily manipulate attributes right from the dom node. There are some aliases that share the syntax of the attributes such as html and text (aliases for innerHTML and textContent). There are others that travel through the dom such as parent (alias for parentNode) and children. Finally, class behaves differently as explained below.

Get attributes

The fetching will always return an array with the element for each of the matched nodes (or undefined if not there):

// Retrieve all the urls from the page
let urls = dom.a.href;     // #attr-list
  // ['', '', ...]

// Get an array of the h2 contents (alias of innerHTML)
let h2s = dom.h2.html;     // #attr-alias
  // ['Level 2 header', 'Another level 2 header', ...]

// Get whether any of the attributes has the value "_blank"
let hasBlank =;    // #attr-value
  // true/false

You also use these:

  • html (alias of innerHTML): retrieve a list of the htmls
  • text (alias of textContent): retrieve a list of the htmls
  • parent (alias of parentNode): travel up one level
  • children: travel down one level

Set attributes

// Set target="_blank" to all links = '_blank';     // #attr-set
dom.class.tableofcontents.html = `
  <ul class="tableofcontents">
    ${ => `
        <a href="#${}">

Remove an attribute

To delete an attribute use the delete keyword:

// Remove all urls from the page
delete dom.a.href;

// Remove all ids


It provides an easy way to manipulate the classes.

Get classes

To retrieve whether a particular class is present or not:

// Get an array with true/false for a single class
let isTest = dom.a.class.test;     // #class-one

For a general method to retrieve all classes you can do:

// Get a list of the classes of each matched element
let arrays = dom.a.class;     // #class-arrays
  // [['important'], ['button', 'cta'], ...]

// If you want a plain list with all of the classes:
let flatten = dom.a.class._flat;     // #class-flat
  // ['important', 'button', 'cta', ...]

// And if you just want an string with space-separated classes:
let text = dom.a.class._text;     // #class-text
  // 'important button cta ...'

Add a class

// Add the class 'test' (different ways)
dom.a.class.test = true;    // #class-make-true
dom.a.class = 'test';       // #class-push

Remove a class

// Remove the class 'test'
dom.a.class.test = false;    // #class-make-false


Did we say it returns a simple array?

dom.a.forEach(link => link.innerHTML = 'I am a link');

But what an interesting array it is; indeed we are also proxy'ing it so you can manipulate its sub-elements straight from the selector:

// Replace all of the link's html with 'I am a link'
dom.a.html = 'I am a link';

Of course we might want to manipulate them dynamically depending on the current value. Just pass it a function:

// Append ' ^_^' to all of the links in the page
dom.a.html = html => html + ' ^_^';

// Same as this:
dom.a.forEach(link => link.innerHTML = link.innerHTML + ' ^_^');

Note: this won't work dom.a.html += ' ^_^'; for more than 1 match (for reasons)

Or get into genetics to manipulate the attributes: = '_blank';

// Only to external sites:
let isOwnPage = el => /^https?\:\/\/mypage\.com/.test(el.getAttribute('href')); = (prev, i, element) => isOwnPage(element) ? '' : '_blank';


You can also handle and trigger events:

// Handle click events for all <a> = e => ...;

// Trigger click event for all <a>;


We are using Jest as a Grunt task for testing. Install Jest and run in the terminal:

grunt watch

Download Details:

Author: franciscop
Source Code: 
License: MIT license

#javascript #es6 #dom 

Samanta  Moore

Samanta Moore


Going Beyond Java 8: Local Variable Type Inference (var) - DZone Java

According to some surveys, such as JetBrains’s great survey, Java 8 is currently the most used version of Java, despite being a 2014 release.

What you are reading is one in a series of articles titled ‘Going beyond Java 8,’ inspired by the contents of my book, Java for Aliens. These articles will guide you step-by-step through the most important features introduced to the language, starting from version 9. The aim is to make you aware of how important it is to move forward from Java 8, explaining the enormous advantages that the latest versions of the language offer.

In this article, we will talk about the most important new feature introduced with Java 10. Officially called local variable type inference, this feature is better known as the **introduction of the word **var. Despite the complicated name, it is actually quite a simple feature to use. However, some observations need to be made before we can see the impact that the introduction of the word var has on other pre-existing characteristics.

#java #java 11 #java 10 #java 12 #var #java 14 #java 13 #java 15 #verbosity

Samanta  Moore

Samanta Moore


Top Tips for Learning Java Programming

If you’re here for the top tips, we assume you’re ahead of the “how to learn Java” part and already boarded on your flight of learning Java. In this lesson, apart from just throwing some do’s and don’ts, we’ll be asking some basic questions that will help you align your path with what’s best for you.

Are you following a plan?

Determining your goal and creating a learning strategy is more significant than you can probably think of. Your ambition, execution, and consistency can make or break your career. So if you want to become a full-time Java Developer shadowing a layout/map goes without saying.

Are you a master of the basics?

Mastering the basics doesn’t necessarily mean learning syntax by heart and not be able to do anything with it. It actually means you’re comfortable working with keywords, know the language protocols, smartly use variables and loops. Know how to choose a data structure depending upon a certain problem. Able to implement object orient approach, since Java is an object-oriented language. Understand encapsulation and how to tamper with it. With this much content freely available widely on the web, newbies are most likely to fell prey to learn more in a shorter period of time. However, you need to understand you can’t build a sustainable building over a weak foundation. Hence, it’s forever helpful to give due time to all the concepts in order to truly “master” them.

#java #learning java programming #java programming #top tips #top tips for learning java programming #programmers

Samanta  Moore

Samanta Moore


Spring Boot and Java 16 Records

In this article, we will discuss Java 16’s newest feature, Records. Then we will apply this knowledge and use it in conjunction with a Spring Boot application.

On March 16th, 2021, Java 16 was GA. With this new release, tons of new exciting features have been added. Check out the release notes to know more about these changes in detail. This article’s focus will be on Java Records, which got delivered with JEP 395. Records were first introduced in JDK 14 as a preview feature proposed by JEP 359, and with JDK 15, they remained in preview with JEP 384. However, with JDK 16, Records are no longer in preview.

I have picked Records because they are definitely the most favored feature added in Java 16, according to this Twitter poll by Java Champion Mala Gupta.

I also conducted a similar survey, but it was focused on features from Java 8 onwards. The results were not unexpected, as Java 8 is still widely used. Very unfortunate, though, as tons of new features and improvements are added to newer Java versions. But in terms of features, Java 8 was definitely a game-changer from a developer perspective.

So let’s discuss what the fuss is about Java Records.

#java #springboot #java programming #records #java tutorials #java programmer #java records #java 16