Question

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 . .

Was it helpful?

Solution

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");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top