Search code examples
springservletsspring-mvcpojo

Spring MVC and handler methods with POJOs


Spring MVC allows to define handler methods with a variety of parameters which are filled in with the appropriate values.

Is it possible to use the same approach to fill in the values into a POJO that is then passed to a handler method?

Currently, I have to do:

@RequestMapping
public ModelMap handle( @RequestParam("user") String user, ... )

What I'd like to do:

class HandlerPojo {
    @RequestParam("user") String user;
    ...
}

@RequestMapping
public ModelMap handle( HandlerPojo pojo )

Solution

  • It is actually pretty simple, even without any Spring @RequestParam annotations inside POJO. What you are looking for is a custom WebArgumentResolver. Here is a complete example:

    @Service
    public class UserArgumentResolver implements WebArgumentResolver {
        @Override
        public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) throws Exception {
            if (methodParameter.getParameterType() == User.class) {
                return new User(webRequest.getParameter("user"));
            }
            return WebArgumentResolver.UNRESOLVED;
        }
    }
    

    Code is rather self-explanatory: if one of the handler parameters is of User type, retrieve request parameter named user and return whatever you want (of course it should be assignable to User. WebArgumentResolver.UNRESOLVED means that the resolver was incapable of handling this parameter and subsequent resolvers should be examined.

    Unfortunately resolver isn't picked up by default, it must be registered:

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="customArgumentResolver" ref="userArgumentResolver"/>
    </bean>
    
    <mvc:annotation-driven />
    

    That's it! Your handler can now look like this:

    @RequestMapping
    public void handle(User user) {
        //...
    }