开发者

Struts | Type casting error

开发者 https://www.devze.com 2023-01-04 16:21 出处:网络
I\'m trying to save a data in a simple form through Hibernate using struts as the controller the problem, but there\'s error occurring when I submit the form

I'm trying to save a data in a simple form through Hibernate using struts as the controller the problem, but there's error occurring when I submit the form

Cannot invoke com.myapp.struts.form.EmployeeEditForm.setEmpdob - argument type mismatch

I assume this is because of the type conflict, because the form field (refer to date of birth field) usually pass a string with the request but in my Form bean the type refers as a Java Data object, so what my real question is where do I type cast this string in to a Data object.

Snippet from my form bean

private Date empdob;

    public void setEmplname(String emplname) {
        this.emplname = emplname;
    }

    public Date getEmpdob() {
        return empdob;
    }    

My action class

public ActionForward saveEmployee(ActionMapping 开发者_开发问答mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) {
        EmployeeEditForm employeeEditForm = (EmployeeEditForm) form;
        BusinessDao businessDao = new BusinessDao();
        businessDao.saveEmployee(employeeEditForm.getEmp());
        return mapping.findForward("showList");
    }

BusinessDao is the DAO to the separation layer to the persistence layer.

Thanks.


You can go about this either by:

1 - have a setter as a String and a getter as Date (you can convert the value from String to Date in the setter);

private Date empdob;

public void setEmpdobString(String s) {
    this.empdob = someDateFormatter.parse(s);
}

public Date getEmpdobDate() {
    return empdob;
}  

2 - have two sets of getters and setters, a pair for String and a pair for Date

   private Date empdob;  

   public Date getEmpdobDate() {  
     return this.empdob;  
   }  

   public void setEmpdobDate(Date empdob) {  
     this.empdob = empdob;  
   }  

   public String getEmpdobString() {  
     return someDateFormatter.format(this.empdob);  
   }  

   public void setEmpdobString(String s) {  
     this.empdob = someDateFormatter.parse(s);  
   }  

My personal choice would be with number 2.

You can also have different date formatters that pick different types of date representations depending on locale (e.g. 12/01/2010 and 01/12/2010 are the same date in different countries).


Actually found this on the web:

Using a Date datatype in FormBean class?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号