然后,如果bindingResult中存在错误,则返回相同的页面,但日期显示如下:
我只想在第二张图片中显示日期,例如第一张图片中的日期。谢谢!
修改
这是包含日期的模型
@Entity
public class Booking implements Serializable {
//
private Date startDate;
private Date finishDate;
//
它们通过Hibernate存储在表中 在控制器中,我必须进行验证转换,因为从mysql返回的日期(我想)。我从db获得的格式是这样的格式"星期六01 00 00:00:00 CEST 2017",而我从datepicker获得的格式是" yyyy-mm-dd HH :MM:SS"
@PostMapping("/rent")
public ModelAndView vehicleRent(@RequestParam("id") long id, @ModelAttribute("newBooking") Booking booking, BindingResult bindingResult) throws ParseException {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
String stringStartDate = dateFormat.format(booking.getStartDate());
Date formattedStartDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(stringStartDate);
if (booking.getStartDate() != null || booking.getFinishDate() != null || booking != null) {
for (Booking b : vehicleBookings) {
if (formattedStartDate.before(b.getFinishDate()) || formattedStartDate.equals(b.getFinishDate())) {
bindingResult.rejectValue("startDate", "validation.booking.startdate.exists");
break;
}
}
}
//
jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () {
$("#startDate,#finishDate").datepicker();
});
<form:form action="${pageContext.request.contextPath}/rent" method="POST" modelAttribute="newBooking">
<div>
<table class="table">
<input id="id" name="id" type="hidden" value="${vehicle.id}"/>
<tr>
<td><form:label path="startDate">Data Inizio</form:label></td>
<td><form:input type="text" id="startDate" name="startDate" path="startDate" data-format="dd/MM/yyyy" /> </td>
<td><form:errors path="startDate" cssStyle="color: #ff0000" /></td>
</tr>
<tr>
<td><form:label path="finishDate">Data Fine</form:label></td>
<td><form:input type="text" id="finishDate" name="finishDate" path="finishDate" /></td>
<td><form:errors path="finishDate" cssStyle="color: #ff0000" /></td>
</tr>
</table>
<input type="submit" value="Invia" />
<br>
<br>
<a href="${pageContext.request.contextPath}/">Torna alla Home</a>
</div>
</form:form>
答案 0 :(得分:0)
您可以尝试将此注释添加到承载@DateTimeFormat
@Entity
public class Booking implements Serializable {
@DateTimeFormat(pattern = "MM/dd/yyyy")
private Date startDate;
@DateTimeFormat(pattern = "MM/dd/yyyy")
private Date finishDate;