DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modern Digital Website Security: Prepare to face any form of malicious web activity and enable your sites to optimally serve your customers.

Containers Trend Report: Explore the current state of containers, containerization strategies, and modernizing architecture.

Low-Code Development: Learn the concepts of low code, features + use cases for professional devs, and the low-code implementation process.

E-Commerce Development Essentials: Considering starting or working on an e-commerce business? Learn how to create a backend that scales.

Related

  • How to Implement Two-Factor Authentication in A Spring Boot OAuth Server? Part 2: Under the Hood
  • Sprinkle Some ELK on Your Spring Boot Logs
  • Extending Spring Boot's Zuul Proxy to Record Requests and Responses
  • Redirecting HTTP Requests With Zuul in Spring Boot

Trending

  • Taming the Virtual Threads: Embracing Concurrency With Pitfall Avoidance
  • The Guide to SRE Principles
  • What Is CI/CD? Beginner’s Guide To Continuous Integration and Deployments
  • Enhancing Observability With AI/ML
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring WebFlux: Writing Filters

Spring WebFlux: Writing Filters

Spring WebFlux's approach to writing filters is a bit different from how you might be used to it in Spring MVC. Let's explore the differences and see what's changed.

Biju Kunjummen user avatar by
Biju Kunjummen
·
Dec. 26, 17 · Tutorial
Like (6)
Save
Tweet
Share
30.3K Views

Join the DZone community and get the full member experience.

Join For Free

Spring WebFlux is the new reactive web framework available as part of Spring 5+. The way filters were written in a traditional Spring MVC based application (Servlet Filter, HandlerInterceptor) is very different from the way a filter is written in a Spring WebFlux-based application, and this post will briefly go over the WebFlux approach to Filters.

Approach 1: WebFilter

The first approach using WebFilter broadly affects all endpoints and covers WebFlux endpoints written in a functional style as well the endpoints that are written using an annotation style. A WebFilter in Kotlin look like this:

@Bean
fun sampleWebFilter(): WebFilter {
    return WebFilter { e: ServerWebExchange, c: WebFilterChain ->
        val l: MutableList<String> = e.getAttributeOrDefault(KEY, mutableListOf())
        l.add("From WebFilter")
        e.attributes.put(KEY, l)
        c.filter(e)
    }
}


The WebFilter adds a request attribute with the value being a collection where the filter is just putting in a message that it has intercepted the request.

Approach 2: HandlerFilterFunction

The second approach is more focused and covers only endpoints written using functional style. Here, specific RouterFunctions can be hooked up with a filter, along the following lines.

Consider a Spring WebFlux endpoint defined the following way:

@Bean
fun route(): RouterFunction<*> = router {
    GET("/react/hello", { r ->
        ok().body(fromObject(
                Greeting("${r.attribute(KEY).orElse("[Fallback]: ")}: Hello")
        ))
    POST("/another/endpoint", TODO())

    PUT("/another/endpoint", TODO())
})

}


A HandlerFilterFunction that intercepts these APIs alone can be added in a highly focused way along these lines:

fun route(): RouterFunction<*> = router {
    GET("/react/hello", { r ->
        ok().body(fromObject(
                Greeting("${r.attribute(KEY).orElse("[Fallback]: ")}: Hello")
        ))
    })

    POST("/another/endpoint", TODO())

    PUT("/another/endpoint", TODO())

}.filter({ r: ServerRequest, n: HandlerFunction<ServerResponse> ->
    val greetings: MutableList<String> = r.attribute(KEY)
            .map { v ->
                v as MutableList<String>
            }.orElse(mutableListOf())

    greetings.add("From HandlerFilterFunction")

    r.attributes().put(KEY, greetings)
    n.handle(r)
})


Note that there is no need to be explicit about the types in Kotlin — I have added it just to be clear about the types in some of the lambda expressions.

Conclusion

The WebFilter approach and the HandlerFilterFunction are very different from the Spring-WebMVC-based approach of writing filters using Servlet Specs or using HandlerInterceptors. This post summarizes the new approaches. For more information, I have samples available in my git repo, which goes over these in more detail.

Filter (software) Spring Framework

Published at DZone with permission of Biju Kunjummen, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Implement Two-Factor Authentication in A Spring Boot OAuth Server? Part 2: Under the Hood
  • Sprinkle Some ELK on Your Spring Boot Logs
  • Extending Spring Boot's Zuul Proxy to Record Requests and Responses
  • Redirecting HTTP Requests With Zuul in Spring Boot

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: