`
gg19861207
  • 浏览: 179997 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

利用反射机制来验证上传文件的格式是否符合要求

阅读更多

public boolean validateFileType(String propertyName) throws Exception{
PropertyDescriptor[] propertydesc = Introspector.getBeanInfo(this.getClass()).getPropertyDescriptors();
boolean exsit = false;
for(PropertyDescriptor property : propertydesc){
if(property.getName().equals(propertyName)){
exsit = true;
Method method = property.getReadMethod();
if(method!=null){
FormFile formfile = (FormFile) method.invoke(this);
if(formfile!=null && formfile.getFileSize()>0){
List<String> arrowType = Arrays.asList("image/bmp","image/png","image/gif","image/jpeg","image/pjpeg");
return arrowType.contains(formfile.getContentType().toLowerCase());
}
}else{
new RuntimeException(propertyName+"属性的getter方法不存在");
}
}
}
if(!exsit) new RuntimeException(propertyName+"属性不存在");
return true;
}

这个方法其实有点过于复杂化了,因为要实现的功能就是判断上传的文件的类型,因为上传的文件在Struts中都是用FormFile来保存的,所以可以有以下的解决方案:

1:在每一个模块的formbean当中都提供一个方法,该方法只要接受FormFile类型的属性,就可以判断该上传文件是什么类型的了。

2:为了实现封装,可以在BaseForm当中提供一个方法,就是上面的这个方法,这个方法使用的是反射机制,就是你只需要传递一个属性的名称,就可以通过反射机制来得到该属性所引用的对象,然后就可以判断该属性的类型,所以在验证的时候,不同的formbean(都继承自BaseForm)就都可以调用上面的这个方法(只要传递的参数不同就可以,比如参数可以是logofile,uploadfile),但是由于反射机制以及上面这个方法的代码决定,logofile,uploadfile都必须是FormFile类型的)

3:以可以有一个简便的方法,就是:

public boolean validateFileType(FormFile formfile) throws Exception{

if(formfile!=null && formfile.getFileSize()>0){
List<String> arrowType = Arrays.asList("image/bmp","image/png","image/gif","image/jpeg","image/pjpeg");
return arrowType.contains(formfile.getContentType().toLowerCase());
}

return true;
}

这样看来的话,第一个用反射机制的方法确实是多此一举,因为完全可以使用上面的这个简单方法来实现该功能,只需要在调用的时候传入不同的FormFile类型的对象就可以了(反射机制的那个方法也是得传入不同的参数,传递的是属性名,即简单方法的传递的参数可能是formfile ,反射机制的方法可能传递的参数是“formfile”)

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics