日期:2014-05-17  浏览次数:20626 次

请教Spring MVC与表单日期提交的问题
1.model:

Java code

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.
HTML code

<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 方法

Java code


@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())

请教这样的需求如何解决??

------解决方案--------------------
在你的Controller里追加
Java code

/**
     * 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));
    }