7

为什么 spring 不绑定我的嵌套对象上的值?

RegistrationBean 上的 SecurityQuestion 对象将问题和答案分别设置为 null、null,尽管在视图中使用 bean 表示法在表单中进行了设置。

豆子:

public class SecurityQuestion {
  SecurityQuestionType type;
  String answer;
}

public class RegistrationBean {
  @Valid
  SecurityQuestion securityQuestion;
  String name;


  public SecurityQuestionType[] getSecurityQuestionOptions() {
    return SecurityQuestionType.values();
  }
}

看法:

<form:form modelAttribute="registrationBean" method="POST">
  <form:select id="securityQuestion" path="securityQuestion.question">
    <c:forEach var="securityQuestionOption" items="${securityQuestionOptions}">
      <form:option value="${securityQuestionOption}">${securityQuestionOption</form:option>
    </c:forEach>
  </form:select>

  <form:input id="securityAnswer" path="securityQuestion.answer" />
  <form:input id="name" path="name" />
</form:form>

控制器:

@RequestMapping(value = URL_PATTERN, method = RequestMethod.POST)
public ModelAndView submit(@Valid final RegistrationBean registrationBean) {
  // registrationBean.getSecurityQuestion().getQuestion() == null
  // registrationBean.getSecurityQuestion().getAnswer() == null
}

解决方案

所有 bean 都必须有所有字段的 getter/setter。Spring 使用默认构造函数,然后使用 setter 从视图中改变对象。

4

1 回答 1

7

您可以尝试为 RegistrationBean 提供适当的 getter/setter 吗?

public class RegistrationBean {
  @Valid
  SecurityQuestion securityQuestion;
  String name;

  public SecurityQuestion getSecurityQuestion(){
        return securityQuestion;
  }
  public void setSecurityQuestion(SecurityQuestion q){
      this.securityQuestion = q;
  }    
  public SecurityQuestionType[] getSecurityQuestionOptions() {
    return SecurityQuestionType.values();
  }
}
于 2010-12-08T19:34:57.407 回答