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 )
It is actually pretty simple, even without any Spring
@RequestParamannotations inside POJO. What you are looking for is a customWebArgumentResolver. Here is a complete example:Code is rather self-explanatory: if one of the handler parameters is of
Usertype, retrieve request parameter nameduserand return whatever you want (of course it should be assignable toUser.WebArgumentResolver.UNRESOLVEDmeans 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:
That’s it! Your handler can now look like this: