java - Spring MVC 将参数绑定(bind)到支持对象

标签 java model-view-controller spring spring-mvc

我正在使用 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/

相关文章:

java - Hibernate 只获取单个子实例

reactjs - react : axios post request with both params and body

PHP 以类作为值提取数组

javascript - Ember.js 中的嵌套 View

java - MyBatis 将属性映射到错误的 Enum

java - 使 JTextArea 在 Swing 中可滚动

java - 我是否正确实现了 ActiveMQ?实现事务处理 session 并重试

spring - 我可以将 Spring 的 MockMvc 与 Jersey 资源一起使用吗?

java - @Autowired 在 Spring 中的类上

spring - java.lang.IllegalStateException : ApplicationEventMulticaster not initialized 错误