在我的数据库表中,我有一列日期类型,我想将值插入此列,因此我应该将字符串转换为日期;为此,我使用类CustomDateEditor,这就是我所做的:
创建一个将转换字符串的控制器:
package gestion.delegation.controller;
import gestion.delegation.domaine.Movement;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.mvc.SimpleFormController;
public class ServiceController extends SimpleFormController{
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
binder.registerCustomEditor(Date.class, editor);
}
}
验证器:
package gestion.delegation.validator;
import java.util.Date;
import gestion.delegation.domaine.Movement;
import gestion.delegation.domaine.User;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class AddActivityValidator implements Validator{
@Override
public boolean supports(Class<?> clazz) {
return Movement.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object obj, Errors err) {
ValidationUtils.rejectIfEmptyOrWhitespace(err, "mode_affectation", "modeaffectattion.requiered", "Choisissez un mode d'affectation");
ValidationUtils.rejectIfEmptyOrWhitespace(err, "nom_etabl", "name.required","Choisissez un nom d'une etablissement");
ValidationUtils.rejectIfEmptyOrWhitespace(err, "cina", "cinn.required","Il faut choisir un fonctionnaire au dessus avant d'essayer de saisir un service");
Movement move = (Movement) obj;
Date debut = move.getDate_debut();
Date fin=move.getDate_fin();
if (debut != null && fin != null && fin.before(debut)) {
err.rejectValue("fin", "notbefore.startdate", "End date cannot be before start date.");
}
}
}
页面 Jsp:
<tr>
<td>Date début :</td>
<td><form:input type="text" name="date" class="tcal"
value="" path="date_debut" /></td>
</tr>
<tr>
<td>Date fin :</td>
<td><form:input type="text" name="date" class="tcal"
value="" path="date_fin" /></td>
<td><form:errors path="date_fin" Class="errorbox" /></td>
</tr>
但执行后我得到这个错误:
Failed to convert property value of type java.lang.String to required type java.util.Date for property date_fin; nested exception is org.springframework.core.convert.ConversionFailedException: Unable to convert value "2013-06-01" from type java.lang.String to type java.util.Date; nested exception is java.lang.IllegalArgumentException
在我看来,控制器不工作或找不到要转换的字段。请问问题出在哪里?谢谢