How to set date type values using Apache Commons BeanUtils,

梦想的初衷 提交于 2019-12-25 00:36:08

问题


I have an Html form with enctype="multipart/form-data" . I have an dto class it has all setter and getters. Since I am submitting form as multipart, getParameter() method will not work,to process html form fields I used Apache Commons BeanUtils. My servlet is as follow,

List<FileItem> items = (List<FileItem>) new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
System.out.println(fieldname);
System.out.println(fieldvalue);
// ... (do your job here)
//getters and setters
try {if((!fieldname.equals("dob"))&&(!fieldname.equals("doj"))){
             BeanUtils.setProperty(teacherInfo, fieldname, fieldvalue);}
} catch (IllegalAccessException e) {
    e.printStackTrace();
} catch (InvocationTargetException e) {
    e.printStackTrace();
}

} else {

        //Code for file upload
 }

My problem is I am unable to process the date type variables , thats why I m ignoring to set two date values in above code and in above code for some html fields, value are not set by Beans setProperty() method . Can any one tell me where I am wrong . .


回答1:


The BeanUtils class provides property setter methods that accept String values, and automatically convert them to appropriate property types. The BeanUtils class relies on conversion methods defined in the ConvertUtils class to perform the actual conversions, and these methods are available for direct use as well.
For dates the DateConverter does not support default String to 'Date' conversion, you will have to register an instance of DateConverter configured with a pattern suitable for the date format you are using, for example:

DateConverter converter = new DateConverter( null );
converter.setPattern("dd/mm/yyyy");
ConvertUtils.register(converter, Date.class);
BeanUtils.setProperty(obj, "date", "07/04/2014");


来源:https://stackoverflow.com/questions/22912437/how-to-set-date-type-values-using-apache-commons-beanutils

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!