有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Struts |类型转换错误

我试图通过Hibernate使用struts作为控制器将数据保存在一个简单的表单中,但在提交表单时出现了错误

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

我假设这是因为类型冲突,因为表单字段(参考date of birth字段)通常与请求一起传递字符串,但在我的表单bean中,类型引用为Java数据对象,所以我真正的问题是我在哪里键入该字符串并将其转换为数据对象

来自我的表单bean的代码片段

private Date empdob;

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

    public Date getEmpdob() {
        return empdob;
    }    

我的动作课

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.

谢谢


共 (2) 个答案

  1. # 1 楼答案

    你可以通过以下两种方式来实现:

    1-将setter作为字符串,getter作为日期(可以在setter中将值从字符串转换为日期)

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

    2-有两套getter和setter,一对用于字符串,一对用于日期

       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);  
       }  
    

    我个人的选择是2号

    您还可以使用不同的日期格式化程序,根据地区选择不同类型的日期表示(例如,2010年1月12日和2010年12月1日在不同国家/地区是同一日期)