我正在使用 Spring MVC,在我的 Controller 中,我希望能够自动将传入参数绑定(bind)到我的 Java 对象。看起来这应该很容易做到。唯一的问题是传入的参数名称(例如“用户名”)可能与 Java 对象中的字段名称(例如“名称”)不完全匹配。
来自 Spring 文档(http://static.springsource.org/spring/docs/2.5.6/reference/mvc.html):
"Spring Web MVC allows you to use any object as a command or form object.... All this means that you don't need to duplicate your business objects' properties as simple, untyped strings in your form objects just to be able to handle invalid submissions, or to convert the Strings properly. Instead, it is often preferable to bind directly to your business objects. "
我该怎么做呢?任何代码或链接表示赞赏。
比如我的业务对象
public class User {
private String username;
private String password;
//getters and setter
}
我的 Controller 正在处理的请求:
example.com/login?name=Steve&pw=1234
我想将“Steve”绑定(bind)到 User.username 并将“1234”绑定(bind)到 User.password。
谢谢。
最佳答案
如果我没记错的话,您可以覆盖 public Object formBackingObject(HttpServletRequest request)
并手动设置命令 POJO。
关于java - Spring MVC 将参数绑定(bind)到支持对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1640853/