今天在写程序时,遇到一个问题,问题如下:
Cannot convert value of type [java.lang.String] to required type [java.lang.Long] for property 'yuid':
问题是再类型转换时出现问题。出现错误的原因是使用了一个外部的框架,封装了Spring的Long型类型转换,而这个框架本身有点问题。所以需要自己写一个类来实现类型转换。
class MyLongEditor extends CustomNumberEditor{
public MyLongEditor() throws IllegalArgumentException {
super(Long.class, true);
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
if(text == null || text.trim().length() == 0){//如果传递的参数为空
setValue(null);
}else{
try{
setValue(Long.parseLong(text));
}catch(NumberFormatException e){
setValue(null);
}
}
}
}
最后在实现了SimpleFormController类的控制器中加入如下函数:
@InitBinder
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder)throws Exception{
binder.registerCustomEditor(Long.class, new MyLongEditor());
}