Spring MVC @PathVariable with dot (.) is getting truncated

后端 未结 17 1322
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 06:00

This is continuation of question Spring MVC @PathVariable getting truncated

Spring forum states that it has fixed(3.2 version) as part of ContentNegotiationManager.

17条回答
  •  [愿得一人]
    2020-11-22 06:36

    As of Spring 5.2.4 (Spring Boot v2.2.6.RELEASE) PathMatchConfigurer.setUseSuffixPatternMatch and ContentNegotiationConfigurer.favorPathExtension have been deprecated ( https://spring.io/blog/2020/03/24/spring-framework-5-2-5-available-now and https://github.com/spring-projects/spring-framework/issues/24179).

    The real problem is that the client requests a specific media type (like .com) and Spring added all those media types by default. In most cases your REST controller will only produce JSON so it will not support the requested output format (.com). To overcome this issue you should be all good by updating your rest controller (or specific method) to support the 'ouput' format (@RequestMapping(produces = MediaType.ALL_VALUE)) and of course allow characters like a dot ({username:.+}).

    Example:

    @RequestMapping(value = USERNAME, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public class UsernameAPI {
    
        private final UsernameService service;
    
        @GetMapping(value = "/{username:.+}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.ALL_VALUE)
        public ResponseEntity isUsernameAlreadyInUse(@PathVariable(value = "username") @Valid @Size(max = 255) String username) {
            log.debug("Check if username already exists");
            if (service.doesUsernameExist(username)) {
                return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
            }
            return ResponseEntity.notFound().build();
        }
    }
    

    Spring 5.3 and above will only match registered suffixes (media types).

提交回复
热议问题