Переплет весеннего списка - PullRequest
0 голосов
/ 03 апреля 2012

Заранее благодарен за любую помощь.

У меня есть следующая ассоциация объекта в моей модели:

public class Contract {
   private Integer id;
   private String name;
   //getters/setters...
}

public class User {
   ....
   private List<Contract> contracts;
   ....
}

Контроллер:

@RequestMapping(....)
public String getUser(@PathVariable Integer userId, Model model) {
   ....
   model.addAttribute(userDao.findUser(userId));
   model.addAttribute("contractsList", contractDao.findAllContracts());
   ....
}

@RequestMapping(....)
public String processUser(@ModelAttribute User user, Model model) {
   ....

   //Create a copy of the user to update...
   User userToUpdate = userDao.findUser(user.getId);

   ....
   userToUpdate.setContracts(user.getContracts());
   //set other properties...

   userDao.updateUser(userToUpdate);

   return "someSuccessView";
} 

@InitBinder
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
   binder.registerCustomEditor(Contract.class, new UserContractsPropertyEditor());
}

Мой PropertyEditor:

public class UserContractsPropertyEditor extends PropertyEditorSupport {

   @Inject ContractDao contractDao;

   @Override
   public void setAsText(String text) throws IllegalArgumentException {
      System.out.println("matching value: " + text);
      if (text != "") {
         Integer contractId = new Integer(text);
         super.setValue(contractDao.findContract(contractId));
      } 
   }

}

Моя форма JSP:

<form:form commandName="user"> 
   <%-- Other fields... --%>
   <form:checkboxes items="${contractsList}" 
      path="contracts" 
      itemValue="id" 
      itemLabel="name" />   
</form:form>

Форма отображается правильно.Таким образом, создается список флажков Контрактов, а правильные проверяются.Проблема в том, что когда я отправляю сообщение, я получаю:

java.lang.IllegalArgumentException: 'items' must not be null
    at org.springframework.util.Assert.notNull(Assert.java:112)
    at org.springframework.web.servlet.tags.form.AbstractMultiCheckedElementTag.setItems(AbstractMultiCheckedElementTag.java:83)
    at org.apache.jsp.WEB_002dINF.jsp._005fn.forms.user_jsp._jspx_meth_form_005fcheckboxes_005f0(user_jsp.java:1192)
    ....

Кажется, что пользовательский редактор свойств выполняет свою работу, и не передаются пустые / пустые строки.

Если форма и контроллер выполняют преобразование при просмотре формы, почему возникают проблемы при обработке формы?Что мне здесь не хватает?

Ответы [ 2 ]

2 голосов
/ 04 апреля 2012

Вы должны убедиться, что вызов getContract () возвращает экземпляр List:

public List<Contract> getContracts() {
    if (contracts == null) contracts = new ArrayList<Contract>();
    return contracts;
}
0 голосов
/ 04 апреля 2012

Спасибо за ваш ответ. Я думаю, что свежий взгляд первым делом с утра снова делает свое дело.

Очевидно, что мой редактор пользовательских свойств не имел понятия, что делать со значением id, которое я передавал, так как он не мог получить доступ к моей DAO / службе. Итак, мне пришлось изменить конструктор:

public class UserContractsPropertyEditor extends PropertyEditorSupport {

   private ContractDao contractDao;

   public UserContractsPropertyEditor(ContractDao contractDao) {
      this.contractDao = contractDao;
   }

   @Override
   public void setAsText(String text) throws IllegalArgumentException {
      Integer contractId = new Integer(text);
      Contract contract = contractDao.findContract(contractId);
      super.setValue(contract);
   }

}

Затем изменил initBinder в моем контроллере:

   @Inject ContractDao contractDao;
   ....    
   @InitBinder
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
       binder.registerCustomEditor(Contract.class, new UserContractsPropertyEditor(this.contractDao));
    }

Может быть, это поможет кому-то еще.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...