Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Spring MVC @RequestMapping throws 406 error for mapping (/user/{username:.+}) when parameter ends with (.pl)

@RequestMapping(value = "/user/{username:.+}", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
User user(@PathVariable String username) {
    User user = userRepository.findByUsername(username);
    if (user == null)
        throw new UserNotFoundException("User not found");

    return user;
}

This is method representing that action. Controller is annotated with @RestController

Solved

Content type negotiation mechanism should be overriden.

Explonation: http://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc

Code:

@Override
  public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer.mediaType("pl", MediaType.APPLICATION_JSON);
  }
like image 209
matiangul Avatar asked Feb 11 '15 14:02

matiangul


1 Answers

Updated answer

PathMatchConfigurer is trying to match every /controller/path.* with every suffix, trying to find content type with ContentNegotiationManager. You can change this behaviour by either disabling this or by making it only attempt that when .* is a registered suffix. See here: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-path-matching

You should either invoke pathMatchConfigurer.setUseRegisteredSuffixPatternMatch(true) or pathMatchConfigurer. setUseSuffixPatternMatch(false)

Old answer :)

I think Spring MVC erroneously assume that .pl is an extansion, and looks up an HTTPMessageConverter for this media type. Creating a converter here wouldn't make sense in this scenario, but maybe marking this as a different media type would work? I would consider this only as a workaround though.

I also think your @RequestMapping value could be simply: value = "/user/{username}" - you are using RegEx .+ for your username variable, which in effect means that you match the whole pattern anyway.

like image 177
theadam Avatar answered Oct 06 '22 08:10

theadam