我正在构建一个Spring MVC(4.2.4.RELEASE)应用程序,我遇到了一些日期字段的问题。
我现在可以创建带日期的对象,我可以用text /'open'html显示日期。我似乎无法填充type = date的输入框。任何人都可以帮助我吗?
所以我的pojo有2个日期字段
@InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(true);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat,false));
}
我已将InitBinder添加到控制器类
<table>
<tr>
<td>Start Date</td>
<td><form:input type="date" path="startDate" id="startDate" /></td>
</tr>
<tr>
<td>End Date</td>
<td><form:input type="date" path="endDate" id="endDate" /></td>
</tr>
</table>
我将pojo作为requestAttribute传递给视图,我没有看到任何问题,因为其他字段正在显示。
在jsp中
{{1}}
未填充字段。我确定这是一个格式问题,好像我把它们转换为标准字符串输入框,删除type =“date”文本框中填充了日期(虽然不是我在任何地方指定的格式!?)。 p>
e.g。 2016年2月1日00:00:00 GMT
我是否需要在其他任何地方'强制'格式化?
答案 0 :(得分:-1)
我找到了答案,对回答我自己的问题表示歉意。也没有把重要的代码放在问题中......我认为这对其他人来说可能很有用......
问题是Spring在使用模型接口时似乎只使用@DateTimeFormat注释。我被要求尝试避免这种情况(没有任何理由我能看到),所以玩了替代方案,解决了HttpServletRequest。 Spring没有拿起日期格式
@RequestMapping(value = "/person/edit/{id}", method=RequestMethod.GET)
public String getPersonForEdit(@PathVariable("id") long id
, HttpServletRequest request) throws IOException
{
...
**request.setAttribute**("person", person);
return "editPerson";
}
当控制器使用Model接口
时 @RequestMapping(value = "/person/edit/{id}", method=RequestMethod.GET)
public String getPersonForEdit(@PathVariable("id") long id
, **Model model**) throws IOException
{
...
**model.addAttribute**("person", person);
return "editPerson";
}
日期格式正常。