В приложении весны mvc, использующем hibernate и jpa, у меня есть форма в приложении весеннего mvc, которому необходимо сохранить текущую дату в поле в строке, которая создается в базовых данных таблицу при отправке формы. У меня есть модель, контроллер и jsp, все настроено, но когда он запускается, я получаю system.out.println(), сообщающий мне, что ошибка локализована, когда дата создания не создается. Как я могу изменить свой код ниже, чтобы дата создания была сгенерирована и отправлена туда, куда ей нужно идти?установка даты в весеннем приложении mvc
Похоже, что функция jqery datepicker не работает в этом коде. Но я не уверен. Свежая точка зрения поможет.
Вот мой JSP:
<script>
$(function() {
$("#created").datepicker({ dateFormat: 'yy/mm/dd'});
});
</script>
<div class="container">
<jsp:include page="../fragments/bodyHeader.jsp"/>
<c:choose>
<c:when test="${document['new']}">
<c:set var="method" value="post"/>
</c:when>
<c:otherwise>
<c:set var="method" value="put"/>
</c:otherwise>
</c:choose>
<h2>
<c:if test="${document['new']}">New </c:if>
Document
</h2>
<form:form modelAttribute="document" method="${method}"
class="form-horizontal">
<div class="control-group" id="patient">
<label class="control-label">Patient </label>
<c:out value="${document.patient.firstName} ${document.patient.lastName}"/>
</div>
<myapp:inputField label="Name" name="name"/>
<myapp:inputField label="Description" name="description"/>
<div class="control-group">
<myapp:selectField name="type" label="Type " names="${types}" size="5"/>
</div>
<td><input type="file" name="file" id="file"></input></td>
<div class="form-actions">
<c:choose>
<c:when test="${document['new']}">
<button type="submit">Add Document</button>
</c:when>
<c:otherwise>
<button type="submit">Update Document</button>
</c:otherwise>
</c:choose>
</div>
</form:form>
<c:if test="${!document['new']}">
</c:if>
<jsp:include page="../fragments/footer.jsp"/>
</div>
</body>
Вот соответствующие части контроллера:
@RequestMapping(value = "/patients/{patientId}/documents/new", method = RequestMethod.GET)
public String initCreationForm(@PathVariable("patientId") int patientId, Map<String, Object> model) {
Patient patient = this.clinicService.findPatientById(patientId);
Document document = new Document();
patient.addDocument(document);
model.put("document", document);
return "documents/createOrUpdateDocumentForm";
}
@RequestMapping(value = "/patients/{patientId}/documents/new", method = RequestMethod.POST)
public String processCreationForm(@ModelAttribute("document") Document document, BindingResult result, SessionStatus status) {
new DocumentValidator().validate(document, result);
if (result.hasErrors()) {
//THIS IS BEING RETURNED BECAUSE DocumentValidator.validate() INDICATES THAT THERE IS NO created DATE
return "documents/createOrUpdateDocumentForm";
}
else {
this.clinicService.saveDocument(document);
status.setComplete();
return "redirect:/patients?patientID={patientId}";
}
}
Вот класс DocumentValidator, который вызывается выше контроллера:
public class DocumentValidator {
public void validate(Document document, Errors errors) {
String name = document.getName();
// name validaation
if (!StringUtils.hasLength(name)) {
System.out.println("--------------------- No Name --------------------------");
errors.rejectValue("name", "required", "required");
}
else if (document.isNew() && document.getPatient().getDocument(name, true) != null) {
System.out.println("--------------------- Name Already Exists --------------------------");
errors.rejectValue("name", "duplicate", "already exists");
}
// type valication
if (document.isNew() && document.getType() == null) {
System.out.println("--------------------- No Type --------------------------");
errors.rejectValue("type", "required", "required");
}
// type valication
if (document.getCreated()==null) {
//THIS LINE IS BEING PRINTED BECAUSE created HAS NOT BEEN POPULATED WITH A VALUE
System.out.println("--------------------- No Created Date --------------------------");
errors.rejectValue("created", "required", "required");
}
}
}
А вот соответствующие части модели, которые являются частью Document.java:
@Column(name = "created")
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
@DateTimeFormat(pattern = "yyyy/MM/dd")
private DateTime created;
public void setCreated(DateTime created) {this.created = created;}
public DateTime getCreated() {return this.created;}
Приведенный выше код компилируется, но когда пользователь нажимает кнопку отправки после ввода информации для загрузки документа, затмение консоль выводит строку из DocumentValidator
, указывая, что поле даты created
не существует.
+1 для добавления понимания. Я поставил большую щедрость на соответствующий вопрос. Не могли бы вы взглянуть на соответствующий вопрос и ответить? Я вручу большую награду человеку, который дает рабочее решение с объяснением. Вот ссылка: http://stackoverflow.com/questions/20586865/document-not-saving-in-spring-jpa-document-manager-application – CodeMed