Pages

Wednesday, June 15, 2011

Preserve TimeStamp value in Struts2

Problem Definition : After page is submitted the value of TimeStamp is not preserve in page. As an additional requirement is that I want TimeStamp value in "MM/dd/yyyy hh:mm:ss a" format on my jsp pages..

File :  xwork-conversion.properties
  
 java.sql.Timestamp = com.myApp.util.MyTimeStampConverter  

Create java file i.e. Class MyTimeStampConverter

Code:

 public class MyTimeStampConverter extends  
     StrutsTypeConverter {  
   private static final SimpleDateFormat sdf =  
     new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");  
   @Override  
   public Object convertFromString(Map context,  
       String[] values, Class toClass)  
       throws TypeConversionException {  
     try {  
       if (values == null || values.length == 0) {  
         return null;  
       }  
       return new java.sql.Timestamp(sdf  
           .parse(values[0]).getTime());  
     } catch (Exception e) {  
       throw new TypeConversionException(e);  
     }  
   }  
   @Override  
   public String convertToString(Map context,  
       Object object)  
       throws TypeConversionException {  
     try {  
       if (object instanceof Timestamp) {  
         return sdf.format(  
             new Date((Timestamp) object).getTime()));  
       }  
       return "";  
     } catch (Exception e) {  
       throw new TypeConversionException(e);  
     }  
   }  
 }  

No comments:

Post a Comment