BeanUtils.populate()空字符串轉換日期的解決辦法


我們在使用beanutils.populate()封裝參數時,如果封裝的字符串是空,在轉換成date時會出現以上異常,此時可以在工具類中添加靜態代碼塊即可解決:注意導入beanutils 包

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.converters.SqlDateConverter;

 

static {
ConvertUtils.register(new SqlDateConverter(null), java.sql.Date.class);

ConvertUtils.register(new Converter() {
@Override
public Object convert(Class type, Object value) {
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try{
return simpleDateFormat.parse(value.toString());
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}, Date.class);
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM