2013-03-04 75 views
2

我在我的struts 2 web應用程序的jsp頁面中使用了兩個struts/dojo datetimepicker。這些允許選擇日期和正確顯示,但是當我提交表單並在變量(與getter和setter)中訪問datetimepickers值與名稱相同的名稱爲jsp形式的datetimepicker時,它將返回空值。在struts 2 action中從struts/dojo datetimepicker獲得null值?

我想如何在Struts動作得到datetimepickers值,然後將它們存儲在MySQL數據庫

我的jsp頁面 - >

<%@taglib prefix="sx" uri="/struts-dojo-tags"%> 
<html> 
<head> 
<sx:head /> 
</head> 
<body> 
<form name="cFrom" method="post" action="saveForm" 
enctype="multipart/form-data"> 
    state Date: <sx:datetimepicker formatLength="medium" value="%{'today'}"  
    name="sDate"></sx:datetimepicker><br/> 
    End Date: <sx:datetimepicker formatLength="medium" name="eDate">  
</sx:datetimepicker><br/> 
<button type="submit">Save</button> 
</form> 
</body> 
</html> 

動作類 - >

import java.util.*; 
public class saveFormAction extends ActionSupport{ 

private static final long serialVersionUID = 1L; 
private Date sDate; 
    private Date eDate; 
    public Date getsDate() { 
    return sDate; 
} 

public void setsDate(Date sDate) { 
    this.sDate = sDate; 
} 

public Date geteDate() { 
    return eDate; 
} 

public void seteDate(Date eDate) { 
    this.eDate = eDate; 
} 
    public String saveForm() throws SQLException{   
    Connection con=DBConnect.makeConnection(); 
    PreparedStatement pst=con.prepareStatement("INSERT INTO saveForm(Start_ON, 
    Expire_On) values(?,?)"); 
    pst.setDate(1, sDate); 
    pst.setDate(2, eDate); 
    int i=0; 
    i=pst.executeUpdate(); 
    if(i>0){ 
     return SUCCESS; 
    } 
    return ERROR; 
    } 
    } 

MySQL表 - >

CREATE TABLE saveform(start_on DATE, Expire_On DATE) 

回答

0

我糾正我的getter和setter和我有下面幾行另一個錯誤做到這一點 - >

pst.setDate(1, sDate); 
pst.setDate(2, eDate); 

我用以下代碼替換了以上代碼行 - >

pst.setDate(1, new java.sql.Date(sDate.getTime())); 
pst.setDate(2, new java.sql.Date(eDate.getTime())); 
0

當您使用private String Date,但您使用private Date sDate時,Datetimepicker會爲您提供2013-03-27T00:00:00+11:00格式的值,這會導致missmacth類型的問題 。要解決這個問題需要從做的DateTimePicker類型轉換到java.util.Date format您可以通過這種方式

String obj = "2013-03-27T00:00:00+11:00"; 
     SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy"); 
     try { 
      SimpleDateFormat parseFormatter = new SimpleDateFormat("yyyy-MM-dd"); 
      //SimpleDateFormat dt = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss+hh:mm"); 
      Date date = parseFormatter.parse(obj); 

      String formattedDate = formatter.format(date); 
      System.out.println(formattedDate); 
     } catch (ParseException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     }