Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC RequestMapping requires trailing slash

There seems to be weird behavior which I can't seem to pinpoint the reason for. When I access a particular url I get a 404 response while other urls that are handled by the same controller class works. I have to add a trailing / to the end of the url in order for the method to be called.

This method DOES NOT get called when accessing localhost:8080/newprofile

 @RequestMapping(value="/newprofile", method=RequestMethod.GET)
    public String newProfile(Model model, Principal principal) {
        return "newprofile";
    }

However, this one DOES get called when accessing localhost:8080/login

@GetMapping("/login")
public String login() {
    return "login";
}

I have tried both GetMapping and RequestMapping but the methods are never called.

Both methods are contained in my controller class

    @Controller
    public class HomeResources {
    //login
    //new profile
        }
like image 682
John Avatar asked Feb 06 '26 08:02

John


2 Answers

There is a setting responsible for such behavior:

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.html#setUseTrailingSlashMatch-boolean-

Just turn it off:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

  @Override
  public void configurePathMatch(PathMatchConfigurer configurer) {
      configurer.setUseTrailingSlashMatch(false);
  }
}
like image 152
Alex Chernyshev Avatar answered Feb 09 '26 07:02

Alex Chernyshev


Note that the default behaviour of setUseTrailingSlashMatch changed from true to false since 6.0 in order to support the deprecation of the property.

If you want this to be enabled you have to set it to true now. But as it is marked deprecated, probably best not to do it and instead follow the advice in this Spring Boot 3.0.0 M4 Release Notes

Developers should instead configure explicit redirects/rewrites through a proxy, a Servlet/web filter, or even declare the additional route explicitly on the controller handler (like @GetMapping("/some/greeting", "/some/greeting/") for more targeted cases.

like image 31
Davide Patti Avatar answered Feb 09 '26 07:02

Davide Patti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!