Raghavendra Raghavendra - 1 year ago 71
Java Question

How to set date type values using Apache Commons BeanUtils,

I have an Html form with

. I have an
class it has all
. Since I am submitting form as multipart,
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();
// ... (do your job here)
//getters and setters
try {if((!fieldname.equals("dob"))&&(!fieldname.equals("doj"))){
BeanUtils.setProperty(teacherInfo, fieldname, fieldvalue);}
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {

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

Answer Source

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();
ConvertUtils.register(converter, Date.class);
BeanUtils.setProperty(obj, "date", "07/04/2014");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download