我有一张有约会的表格。我注册了一个customDateEditor,用于将用户输入String转换为日期。
public class CategoryExclusionFormController extends SimpleFormController {
private ModelMap modelMap = new ModelMap();
protected final Log logger = LogFactory.getLog(getClass());
private ExclusionDAO exclusionDAO;
public ExclusionDAO getExclusionDAO() {
return exclusionDAO;
}
public void setExclusionDAO(ExclusionDAO exclusionDAO) {
this.exclusionDAO = exclusionDAO;
}
public ModelAndView onSubmit(Object command)
throws ServletException {
return new ModelAndView(new RedirectView(getSuccessView()));
}
protected Object formBackingObject(HttpServletRequest request) throws ServletException {
CatExclCriteria catExcl = new CatExclCriteria();
return catExcl;
}
@Override
protected Map referenceData(HttpServletRequest request) throws Exception {
modelMap.put("categories", exclusionDAO.getCategories());
modelMap.put("statuses", exclusionDAO.getStatuses());
return modelMap;
}
@InitBinder
public void initBinder(WebDataBinder binder) {
DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class,"endDate", new CustomDateEditor(
dateFormat, false));
}
}
我的jsp有 以MM-dd-YYYY格式输入开始日期
<form:input path="endDate" />
</form:form>
我的appname-servlet.xml有
<bean name="/categoryExcl.htm" class="com.lsr.CategoryExclusionFormController">
<property name="sessionForm" value="true"/>
<property name="commandName" value="catExcl"/>
<property name="commandClass" value="com.lsr.model.CatExclCriteria"/>
<property name="formView" value="categoryExclusion"/>
<property name="successView" value="home.htm"/>
<property name="exclusionDAO" ref="exclusionDAO"/>
</bean>
当我输入日期并点击提交时,我收到以下错误
Field error in object 'catExcl' on field 'endDate': rejected value [05-12-2011];
codes [typeMismatch.catExcl.endDate,typeMismatch.endDate,typeMismatch.java.util.Date,typeMismatch];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes
[catExcl.endDate,endDate]; arguments []; default message [endDate]];
default message
[Failed to convert property value of type [java.lang.String] to required type
[java.util.Date] for property 'endDate'; nested exception is
java.lang.IllegalArgumentException:
Cannot convert value of type [java.lang.String] to required type [java.util.Date] for
property 'endDate': no matching editors or conversion strategy found],
我不确定为什么它没有使用customDateEditor。我已经看到相关问题的答案,但我找不到错误。
答案 0 :(得分:4)
在黑暗中拍摄;尝试简单地覆盖initBinder()方法:
@Override
public void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class,"endDate", new CustomDateEditor(
dateFormat, false));
}