Processing Date in Struts 1 ActionForm

3.4k Views Asked by At

I have problem on processing input request parameter (of course it's type String) to java.util.Date. I thought that following code added to my bean might solve this problem, but I was wrong:

public Date getDate() {
    return date;
}

public void setDate(Date date) {
    this.date = date;
}

public void setDate(String dateString) {
    try {
        date = DateFormat.getDateInstance().parse(dateString);
    } catch (ParseException e) {
        date = new Date();
    }
}

It throws an exception after submiting form:

javax.servlet.ServletException: BeanUtils.populate
org.apache.struts.util.RequestUtils.populate(RequestUtils.java:469)
org.apache.struts.action.RequestProcessor.processPopulate(RequestProcessor.java:818)

java.lang.IllegalArgumentException: Cannot invoke com.epam.testapp.model.News.setDate - argument type mismatch
org.apache.commons.beanutils.PropertyUtilsBean.invokeMethod(PropertyUtilsBean.java:1778)
org.apache.commons.beanutils.PropertyUtilsBean.setSimpleProperty(PropertyUtilsBean.java:1759)
org.apache.commons.beanutils.PropertyUtilsBean.setNestedProperty(PropertyUtilsBean.java:1648)
org.apache.commons.beanutils.PropertyUtilsBean.setProperty(PropertyUtilsBean.java:1677)

Is this fundamental of struts 1 form that this code won't work because of mismatch of returning getter and accepting setter parameter types? How can I solve this problem ? I don't want at all to make method named like setStringDate(String stringDate(){...} and think on every page which method should I call :(

2

There are 2 best solutions below

3
On BEST ANSWER

Date object cannot be a property in struts as date format can vary (depending on specification). Some may have dd-MM-yyyy, dd-MMMM-yy, etc.

I would suggest having a property:

private String date;

public String getDate() { return date; }

public void setDate(String date) { this.date = date; }

And in your action, convert the date string into Date object.

0
On

As per my knowledge I think , overloaded methods don't work very well in form beans .Try naming the two methods differently, and I think you'll have better luck.