请教Spring MVC与表单日期提交的问题

macrotea-cn 2011-09-27 12:50:02
1.model:


public class UserType implements Serializable {
private static final long serialVersionUID = 1L;

private int id;
private String typeName;
private String remark;
private Date addDate;
private Date editDate;


2.

<form name="userTypeForm" method="post" action="create.do">
<fieldset>
<legend>用户类型</legend>
<p>
<label for="typeName">类型名称:</label><br />
<input name="typeName" type="text" value="${userType.typeName }"/>
</p>
<p>
<label for="remark">备注:</label><br />
<input name="remark" type="text" value="${userType.remark }"/>
</p>
<p>
<label for="addDate">添加时间:</label><br /> 2011-9-2 10:19:23 <br />
<input name="addDate" type="text" value="<fmt:formatDate value="${userType.addDate}" type="both" />"/>
</p>
<p>
<label for="editDate">编辑时间:</label><br />
<input name="editDate" type="text" value="<fmt:formatDate value="${userType.editDate}" type="both" />"/>
</p>
<p>
<input type="submit" value="提交"/>
</p>
</fieldset>
</form>


3.controller 方法



@RequestMapping(value = "create", method = RequestMethod.POST)
public String create(@ModelAttribute UserType userType , Model model) {//BindException exception

}



4.问题

一般情况下,添加时间和更新时间都不需要用户填写,但是如果去掉了这两个input的话,将会出现异常,提示字符串""向Date类型转换异常,毕竟用户都没有输入,因此提示这个情有可原,然而这两个时间是不需要用户输入的,我希望在方法体中手工设置:setAddDate(new Date())和setEditDate(new Date())

请教这样的需求如何解决??
...全文
446 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
nuoboxgx 2011-10-09
  • 打赏
  • 举报
回复
在你的Controller里追加

/**
* Set up a custom property editor for converting form inputs to real objects
*
* @param request the current request
* @param binder the data binder
*/
@InitBinder
public void InitBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
// 不要删除下行注释!!! 将来"yyyy-MM-dd"将配置到properties文件中
//SimpleDateFormat dateFormat = new SimpleDateFormat(getText("date.format", request.getLocale()));
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, null, new CustomDateEditor(dateFormat, true));
}

就可以了 在@ModelAttribute里自动转换了
当然你要保证前台yyyy-MM-dd格式或者空
macrotea-cn 2011-09-27
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 fengyun111999 的回复:]

如果只是显示时间就没有必要用input框
可以加个if判断,若时间为空,就显示一个固定值或者显示为空,
不为空才进行时间格式转换
[/Quote]

这不是好的解决放放假
添加时间需在业务逻辑层准备执行插入设置的
fengyungl 2011-09-27
  • 打赏
  • 举报
回复
如果只是显示时间就没有必要用input框
可以加个if判断,若时间为空,就显示一个固定值或者显示为空,
不为空才进行时间格式转换

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧