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 )
The documentation you linked to says:
Handler methods that are annotated with @RequestMapping can have very flexible signatures. [...]
- Command or form objects to bind parameters to: as bean properties or fields, with customizable type conversion [...]
You can't use the @RequestMapping annotation on the properties/fields of the POJO like you did in your example, but if the property names of the POJO map the parameter names, the POJO will be instantiated and populated by Spring properly.
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) {
//...
}
This is not possible, the @RequestMapping is pulling parameters specified in the request and assigning their values to a java variable. You can't pass a pojo in a request, because the pojo does not exist on the client. Maybe look at passing some json back and deserializing it into a pojo using jackson or gson.
精彩评论