解决webwork2中不能正确截获由js形成的日期属性问题
[方法]将PeriodView日期类型属性设为String,在页面用正则表达式判断,params和model-driven拦截器
拦截属性(String类型)后再转变为Date类型设置到Period对象中,具体实现:
[1]在页面写js
<script language="javascript" type="text/javascript">
function strDateTime(id) {
var str = document.getElementById(id).value;
var reg = /^(/d{4})(-|//)(/d{1,2})/2(/d{1,2}) (/d{1,2}):(/d{1,2}):(/d{1,2})$/;
var r = str.match(reg);
if(r==null)return false;
var d= new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]);
return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()== r[7])
}
function displayInfo(){
alert("时间格式错误,请仿照这样的格式输入:2006-8-20 12:12:00");
}
function validateForm(){
if (!strDateTime("initiatedEndDate")){
displayInfo();
document.getElementById("initiatedEndDate").focus();
return false;
}
}
</script>
[2]在action 中写:
public String execute() {
period = new Period();
period.setDescription("");
period.setInitiatedEndDate(getDate(model.getInitiatedEndDate()));
period.setPurchasedEndDate(getDate(model.getPurchasedEndDate()));
period.setSerialNum(model.getSerialNum());
period.setUploadEndDate(getDate(model.getUploadEndDate()));
period.setDrawingLotDate(getDate(model.getDrawingLotDate()));
period.setCat(lotCatManager.get(model.getCatId()));
periodManager.insertPeriod(period);
return SUCCESS;
}
private Date getDate(String strDate){
Date date = DateUtil.toCalendar(strDate).getTime();
if (date ==null) return new Date();
return date;
}
其中的DateUtil.toCalendar(String strDate)方法:
/**
* 把一个日期字符串转换成Calendar形式
*
* @param strDate
* @return
*/
public static final SimpleDateFormat dateTimeFormatter = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
...
public static final Calendar toCalendar(String strDate) {
Calendar cale = null;
try {
Date thisDate = dateTimeFormatter.parse(strDate);
cale = Calendar.getInstance();
cale.setTime(thisDate);
} catch (Exception e) {
return null;
}
return cale;
}