Search code examples
javaspringspring-mvcspring-bootspring-restcontroller

WebRequest on @RequestBody object


In Spring MVC. I'm able to use the WebRequest as a parameter that will automatically be set (along with other things such as Locale etc.).

I'm also using @RequestBody to pass in a JSON object which describes what and how data should be fetched.

Is it possible to get Spring to automatically set the WebRequest directly on the @RequestBody object EntriesRequestDTO (I would make a WebRequest field on EntriesRequestDTO). This would allow me to hide some complexity since I often need to get an attribute from WebRequest.

 @RequestMapping(value = "/entries", method = { RequestMethod.POST })
    public EntriesDTO getEntries(@RequestBody EntriesRequestDTO request, WebRequest webRequest){
   ...
}

Solution

  • I ended up making a custom HttpMessageConverter. It is not a very general solution, but it works for me:

    @Configuration
    public class WebConfiguration extends WebMvcConfigurationSupport {
        @Bean
        public DTOJackonMessageConverter customJackson2HttpMessageConverter() {
            return new DTOJackonMessageConverter();
        }
    
        @Override
        public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
            converters.add(customJackson2HttpMessageConverter());
            super.addDefaultHttpMessageConverters(converters);
        }
    }
    

    The DTOJacksonMessageConverter extends MappingJackson2HttpMessageConverter and overrides read method.