Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

Spring 5 introduced WebFlux, a new framework that lets us build web applications using the reactive programming model.

In this tutorial, we’ll see how we can apply this programming model to functional controllers in Spring MVC.

2. Maven Setup

We’ll be using Spring Boot to demonstrate the new APIs.

This framework supports the familiar annotation-based approach of defining controllers. But it also adds a new domain-specific language that provides a functional way of defining controllers.

From Spring 5.2 onwards, the functional approach will also be available in the Spring Web MVC framework. As with the WebFlux module, RouterFunctions and RouterFunction are the main abstractions of this API.

So let’s start by importing the spring-boot-starter-web dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

3. RouterFunction vs @Controller

In the functional realm, a web service is referred to as a route and the traditional concept of @Controller and @RequestMapping is replaced by a RouterFunction.

To create our first service, let’s take an annotation-based service and see how it can be translated into its functional equivalent.

We’ll use the example of a service that returns all the products in a product catalog:

@RestController
public class ProductController {

    @RequestMapping("/product")
    public List<Product> productListing() {
        return ps.findAll();
    }
}

Now, let’s look at its functional equivalent:

@Bean
public RouterFunction<ServerResponse> productListing(ProductService ps) {
    return route().GET("/product", req -> ok().body(ps.findAll()))
      .build();
}

3.1. The Route Definition

We should note that in the functional approach, the productListing() method returns a RouterFunction instead of the response body. It’s the definition of the route, not the execution of a request.

The RouterFunction includes the path, the request headers, a handler function, which will be used to generate the response body and the response headers. It can contain a single or a group of web services.

We’ll cover groups of web services in more detail when we look at Nested Routes.

In this example, we’ve used the static route() method in RouterFunctions to create a RouterFunction. All the requests and response attributes for a route can be provided using this method.

3.2. Request Predicates

In our example, we use the GET() method on route() to specify this is a GET request, with a path provided as a String.

We can also use the RequestPredicate when we want to specify more details of the request.

For example, the path in the previous example can also be specified using a RequestPredicate as:

RequestPredicates.path("/product")

Here, we’ve used the static utility RequestPredicates to create an object of RequestPredicate.

3.3. Response

Similarly, ServerResponse contains static utility methods that are used to create the response object.

In our example, we use ok() to add an HTTP Status 200 to the response headers and then use the body() to specify the response body.

Additionally, ServerResponse supports the building of response from custom data types using EntityResponse. We can also use Spring MVC’s ModelAndView via RenderingResponse.

3.4. Registering the Route

Next, let’s register this route using the @Bean annotation to add it to the application context:

@SpringBootApplication
public class SpringBootMvcFnApplication {

    @Bean
    RouterFunction<ServerResponse> productListing(ProductController pc, ProductService ps) {
        return pc.productListing(ps);
    }
}

Now, let’s implement some common use cases we come across while developing web services using the functional approach.

4. Nested Routes

It’s quite common to have a bunch of web services in an application and also have them divided into logical groups based on function or entity. For example, we may want all services related to a product, to begin with,/product.

Let’s add another path to the existing path /product to find a product by its name:

public RouterFunction<ServerResponse> productSearch(ProductService ps) {
    return route().nest(RequestPredicates.path("/product"), builder -> {
        builder.GET("/name/{name}", req -> ok().body(ps.findByName(req.pathVariable("name"))));
    }).build();
}

In the traditional approach, we’d have achieved this by passing a path to @Controller. However, the functional equivalent for grouping web services is the nest() method on route().

Here, we start by providing the path under which we want to group the new route, which is /product. Next, we use the builder object to add the route similarly as in the previous examples.

The nest() method takes care of merging the routes added to the builder object with the main RouterFunction.

5.  Error Handling

Another common use case is to have a custom error handling mechanism. We can use the onError() method on route() to define a custom exception handler.

This is equivalent to using the @ExceptionHandler in the annotation-based approach. But it is far more flexible since it can be used to define separate exception handlers for each group of routes.

Let’s add an exception handler to the product search route we created earlier to handle a custom exception thrown when a product is not found:

public RouterFunction<ServerResponse> productSearch(ProductService ps) {
    return route()...
      .onError(ProductService.ItemNotFoundException.class,
         (e, req) -> EntityResponse.fromObject(new Error(e.getMessage()))
           .status(HttpStatus.NOT_FOUND)
           .build())
      .build();
}

The onError() method accepts the Exception class object and expects a ServerResponse from the functional implementation.

We have used EntityResponse which is a subtype of ServerResponse to build a response object here from the custom datatype Error. We then add the status and use EntityResponse.build() which returns a ServerResponse object.

6. Filters

A common way of implementing authentication as well as managing cross-cutting concerns such as logging and auditing is using filters. Filters are used to decide whether to continue or abort the processing of the request.

Let’s take an example where we want a new route that adds a product to the catalog:

public RouterFunction<ServerResponse> adminFunctions(ProductService ps) {
    return route().POST("/product", req -> ok().body(ps.save(req.body(Product.class))))
      .onError(IllegalArgumentException.class, 
         (e, req) -> EntityResponse.fromObject(new Error(e.getMessage()))
           .status(HttpStatus.BAD_REQUEST)
           .build())
        .build();
}

Since this is an admin function we also want to authenticate the user calling the service.

We can do this by adding a filter() method on route():

public RouterFunction<ServerResponse> adminFunctions(ProductService ps) {
   return route().POST("/product", req -> ok().body(ps.save(req.body(Product.class))))
     .filter((req, next) -> authenticate(req) ? next.handle(req) : 
       status(HttpStatus.UNAUTHORIZED).build())
     ....;
}

Here, as the filter() method provides the request as well as the next handler, we use it to do a simple authentication which allows the product to be saved if successful or returns an UNAUTHORIZED error to the client in case of failure.

7. Cross-Cutting Concerns

Sometimes, we may want to perform some actions before, after or around a request. For example, we may want to log some attributes of the incoming request and outgoing response.

Let’s log a statement every time the application finds a matching for the incoming request. We’ll do this using the before() method on route():

@Bean
RouterFunction<ServerResponse> allApplicationRoutes(ProductController pc, ProductService ps) {
    return route()...
      .before(req -> {
          LOG.info("Found a route which matches " + req.uri()
            .getPath());
          return req;
      })
      .build();
}

Similarly, we can add a simple log statement after the request has been processed using the after() method on route():

@Bean
RouterFunction<ServerResponse> allApplicationRoutes(ProductController pc, ProductService ps) {
    return route()...
      .after((req, res) -> {
          if (res.statusCode() == HttpStatus.OK) {
              LOG.info("Finished processing request " + req.uri()
                  .getPath());
          } else {
              LOG.info("There was an error while processing request" + req.uri());
          }
          return res;
      })          
      .build();
    }

8. Conclusion

In this tutorial, we started with a brief introduction to the functional approach for defining controllers. We then compared Spring MVC annotations with their functional equivalents.

Next, we implemented a simple web service that returned a list of products with a functional controller.

Then we proceeded to implement some of the common use cases for web service controllers, including nesting routes, error handling, adding filters for access control, and managing cross-cutting concerns like logging.

As always the example code can be found over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!