javaspringhttp-request-parameters

Convert Spring RequestParam map into custom Map wrapper object


I'm working on a Spring application, and I saw that you can declare @RequestParam Map<String, String> to have Spring automatically convert all parameters into that Map

I made a wrapper class for it as well to add convenience functionality like automatic parsers, but I was wondering if there was a way to get Spring to automatically convert the entire Map into the wrapper

I've seen other implementations of people making a POJO for data mapping, but that's not quite what I'm going for

The code for the wrapper is as follows:

public class RequestMap {
    private final Map<String, String> innerMap;

    public RequestMap(Map<String, String> map) {
        innerMap = map;
    }

    (getter/parser methods, and accessors for inner map)
}

What I'd ideally like to be able to do is:

// Old method
@PostMapping()
public Model showPage(@RequestParam Map<String, String> requestMap) {
    RequestMap request = new RequestMap(requestMap);

    // Do stuff
}

// What I'm trying to get
@PostMapping()
public Model showPage(RequestMap request) {
    // Do stuff
}

Solution

  • You can register a custom HandlerMethodArgumentResolver

    See the custom argument resolver example on Baeldung's website

    Eg

    @Configuration
    public class MyWebMvcConfigurer implements WebMvcConfigurer {
        @Override
        public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
            HandlerMethodArgumentResolver resolver = new HandlerMethodArgumentResolver() {
                @Override
                public boolean supportsParameter(MethodParameter methodParameter) {
                    return RequestMap.class.equals(methodParameter.getParameterType());
                }
            
                @Override
                public Object resolveArgument(MethodParameter param, ModelAndViewContainer mvContainer, NativeWebRequest request, WebDataBinderFactory binderFactory) {
                    HttpServletRequest httpRequest = request.getNativeRequest(HttpServletRequest.class);
                    return new RequestMap(httpRequest.getParameterMap());
                }
            };
            argumentResolvers.add(resolver);
        }
    }