Spring-mvc,表单绑定

时间:2014-12-05 10:51:55

标签: java spring jsp spring-mvc

我有一个显示目的地的JSP,左边的列表和中间的表格。表单绑定到从列表中选择的目标,并且运行良好。

但是,当我提交表单时,所有值都为空。就像绑定没有完成一样。

public class DestinationsCtrl {
  @RequestMapping("/{id}")
  public String edit(@PathVariable("id")String id, Model model) {
    if ( "new".equals(id) ) {
      model.addAttribute("model", new AdministrationModel(destinations.list(), new EmptyDestination()));
    } else {
      model.addAttribute("model", new AdministrationModel(destinations.list(), destinations.get(id)));
    }
    return "administration";
  }


  @RequestMapping(value = "/", method = POST)
  // "form" or "model.form" give me an empty 'form'
  public String create(@ModelAttribute("model.form") DestinationForm form, Errors errors, RedirectAttributes messages, HttpServletRequest request) {
    LOG.info("Creating new destination [name:{}, contact.email:{}], {} errors.", form.getName(), form.getContactEmail(), errors.getErrorCount());
    destinations.store( new Destination(form.getName(),
            new Contact(form.getContactEmail(), form.getContactName())) );
    return null;
  }
}

public class AdministrationModel {
  private final Set<Destination> destinations = new TreeSet<Destination>(/*comparator*/);
  private final Destination selected;
  private DestinationForm form;

  public DestinationForm getForm() {
    if ( form==null ) {
        form = new DestinationForm(getSelected());
    }
    return form;
  }

  // Getters and some utility logic. NO SETTERS
}


public class DestinationForm {
  private String template = "";
  private String name = "";
  private String contactEmail = "";
  private String contactName = "";
  private String description = "";

  public DestinationForm() {
    this(null);
  }

  public DestinationForm(final Destination destination) {
    if (destination != null) {
      name = destination.getName();
      contactEmail = destination.getContact().getEmail();
      contactName = destination.getContact().getName();
    }
  }

  // Getters and setters
}

最后,JSP:

.. A lot of other tags to make thge page looks good 
.. And a <c:forEach items=${model.destinations}> to create the left list

<f:form role="form" method="${method}" action="${action}" modelAttribute="model.form">
  <h1 class="page-header">
    <f:input path="name" type="text" placeholder="New destination" />
  </h1>
  .. other input for contact name and email

  <input type="submit" class="btn btn-default">Save</input>
</f:form>

控制器上的日志始终报告Creating new destination [name:, contact.email:], 0 errors. 我也没有例外或抱怨春天。

0 个答案:

没有答案