Spring MVC 和带有 POJO 的处理程序方法
Spring MVC 允许定义 具有各种参数的处理方法,这些参数填充有适当的值。
是否可以使用相同的方法将值填充到 POJO 中,然后传递给处理程序方法?
目前,我必须做:
@RequestMapping
public ModelMap handle( @RequestParam("user") String user, ... )
我想做的事情:
class HandlerPojo {
@RequestParam("user") String user;
...
}
@RequestMapping
public ModelMap handle( HandlerPojo pojo )
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 )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您链接到的文档说:
您不能像在示例中那样在 POJO 的属性/字段上使用 @RequestMapping 注释,但如果 POJO 的属性名称映射参数名称,则 POJO 将被实例化并由 Spring 正确填充。
The documentation you linked to says:
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.
它实际上非常简单,即使 POJO 中没有任何 Spring
@RequestParam
注解。您正在寻找的是自定义WebArgumentResolver
。这是一个完整的示例:代码相当不言自明:如果处理程序参数之一是
User
类型,则检索名为user
的请求参数并返回您想要的任何内容(当然,它应该分配给User
。WebArgumentResolver.UNRESOLVED
意味着解析器无法处理此参数,不幸的是,后续解析器不会被检查 。默认,它必须注册:
就是这样!您的处理程序现在看起来像这样:
It is actually pretty simple, even without any Spring
@RequestParam
annotations 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
User
type, retrieve request parameter nameduser
and return whatever you want (of course it should be assignable toUser
.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:
That's it! Your handler can now look like this:
这是不可能的,@RequestMapping 正在拉取请求中指定的参数并将它们的值分配给 java 变量。您不能在请求中传递 pojo,因为客户端上不存在该 pojo。也许看看传回一些 json 并使用 jackson 或 gson 将其反序列化为 pojo。
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.