How To Handle URL Trailing Slash Changes in Spring Boot 3

How To Handle URL Trailing Slash Changes in Spring Boot 3

Understand how to handle URL trailing slash changes in Spring Boot 3.

Context

If you are upgrading your web application to Spring Boot 3 then you need to review the changes that were introduced related to URL matching.

Earlier trailing slash match configuration for URLs was set to true by default but this configuration option has been as a part of Spring Framework 6.x and it’s default value is set to false due to which you may observe HTTP 404 error for the requests that you are receiving.

Example

GET /some/greeting
Example 1
GET /some/greeting/
Example 2

In Example 2, you will see we have one additional slash at the end of the URL. Before Spring Framework 6.x, the above two URLs were treated as same but starting with Spring Boot 3.x, these URLs will be treated as different URLs and this will result in HTTP 404 error.



Ways to Handle

Handle URL Trailing Slash Changes
Handle URL Trailing Slash Changes

Adding URLs in Controller Handler

In this method, you need to add an additional route explicitly on the controller handler. This means you need to add both URLs for all the controller endpoints.

@GetMapping({"/some/greeting", "/some/greeting/"})
public String sendGreetings() {
  return "Hello User";
}
Java

In the above example, you can see we have explicitly specified two URLs for our endpoint.



Update Global Spring MVC Configuration

In this method, instead of adding additional URLs, we will change the default configuration related to trailing slash match and set it to true. This will restore the old configuration that was present before Spring Framework 6.x. After updating this configuration the URLs with trailing slash and URLs without trailing slash will be treated as same.

We can update this configuration in the case of Spring MVC as well as in the case of Spring WebFlux.

Spring MVC

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
      configurer.setUseTrailingSlashMatch(true);
    }
    
}
Java

Spring WebFlux

@Configuration
public class WebConfiguration implements WebFluxConfigurer {

    @Override
    public void configurePathMatching(PathMatchConfigurer configurer) {
      configurer.setUseTrailingSlashMatch(true);
    }
    
}
Java

Summary

When upgrading to Spring Boot 3, review URL matching changes: trailing slash match config default is now false, so update your configurations to avoid HTTP 404 errors.



Learn More

#

Curious to Learn Something New?

Check out how we can extend default tags in Spring Boot 3.

One Response

Add a Comment

Your email address will not be published.