我需要你的帮助。在我的JSP中有形式:form,在form里面:form是form:输入日期..如下:
<form:form modelAttribute="personalTask" method="POST" action="${pageContext.request.contextPath}/taskmgr/add">
(...)
<div class="input-group">
<form:input path="startDate" type="date" id="startDateTimePicker" name="search_message[displayDateFrom]" placeholder="YYYY-MM-DD hh:mm:ss" class="input-sm form-control"></form:input>
<div class="input-group-addon">
<span class="glyphicon glyphicon-calendar"> </span>
</div>
</div>
(...)
</form:form>
在控制器中我有方法:
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addProfileTask(@ModelAttribute("personalTask")PersonalTask task, Principal principal){
return "taskManager";
}
PersonalTask看起来像:
public class PersonalTask{
(...)
@Column(name = "START_DATE", columnDefinition="TIMESTAMP", nullable = false)
private LocalDateTime startDate;
(...)
public LocalDateTime getStartDate() {
return startDate;
}
public void setStartDate(LocalDateTime startDate) {
this.startDate = startDate;
}
(...)
}
问题是......如何从JSP传递datetime并使用@ModelAttribute(“personalTask”)绑定PersonalTask任务??
答案 0 :(得分:2)
使用Spring Converters,spring已经有Date
和Time
数据类型的内置转换器@DateTimeFormat
,从文档中已经支持java.time.LocalDateTime
支持按样式模式,ISO日期时间模式或自定义格式模式字符串进行格式化。可以应用于java.util.Date,java.util.Calendar,java.lang.Long,Joda-Time值类型;从Spring 4和JDK 8开始,到JSR-310 java.time类型。
示例:
public class PersonalTask{
@DateTimeFormat(pattern="dd/MM/yyyy") // or any pattern you prefer
@Column(name = "START_DATE", columnDefinition="TIMESTAMP", nullable = false)
private LocalDateTime startDate;
}
答案 1 :(得分:0)
可以使用格式化字符串创建新的LocalDateTime对象:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(dateInitializer, formatter);
使用从JSP表单中获取的日期来实例化一个新的LocalDateTime对象并将其传递给PersonTask对象
将字符串从日期输入绑定到PersonTask中的字段,并使用它来实例化LocalDateTime对象:
public class PersonalTask{
(...)
private String dateInitializer;
@Column(name = "START_DATE", columnDefinition="TIMESTAMP", nullable = false)
private LocalDateTime startDate;
public PersonalTask(){
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
startTime = LocalDateTime.parse(dateInitializer, formatter);
}
(...)
public LocalDateTime getStartDate() {
return startDate;
}
public void setStartDate(LocalDateTime startDate) {
this.startDate = startDate;
}
(...)
}
在JSP中:
<form:input path="dateInitializer" type="date" id="startDateTimePicker" name="search_message[displayDateFrom]" placeholder="YYYY-MM-DD hh:mm:ss" class="input-sm form-control"></form:input>