문제

Why is spring not binding the values on my nested object?

The SecurityQuestion object on the RegistrationBean is set with question and answer as null, null, respectively, despite setting then in form using bean notation in the view.

Beans:

public class SecurityQuestion {
  SecurityQuestionType type;
  String answer;
}

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


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

View:

<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>

Controller:

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

Solution

All beans have to have getters/setters for all fields. Spring uses the default constructor and then uses the setters to mutate the object from the view.

도움이 되었습니까?

해결책

Can you try giving the RegistrationBean an appropriate 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();
  }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top