Saturday, June 25, 2011

Write your DateConverter for Struts2




I didn't see Struts2 provide a good DateConverter implementation, so I wrote my own. It also use ResourceBundle to work with i18n requirements. Below is my DateConverter.java, and don't forget to add your own package path.

import java.text.ParseException;
import java.util.Date;
import java.util.Map;
import java.util.ResourceBundle;

import org.apache.struts2.util.StrutsTypeConverter;

import util.DateUtil;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;


public class DateConverter extends StrutsTypeConverter {
  
  private static Logger LOG = LoggerFactory.getLogger(DateConverter.class);
  
  @Override
  /**
   * Converts one or more String values to the specified class.
   *
   * @param context the action context
   * @param values  the String values to be converted, such as those submitted from an HTML form
   * @param toClass the class to convert to
   * @return the converted object
   */
  public Object convertFromString(Map context, String[] values, Class toClass) {
    
    Date returnObject = null;
    String value = values[0];
    if (value != null && !value.trim().equals("")) {
      try {
        returnObject = DateUtil.parseDate(value, getDatePattern());
      } catch (ParseException e) {
        // Just to ignore the parse exception
      }
    }
    return returnObject;
  }

  @Override
  /**
   * Converts the specified object to a String.
   *
   * @param context the action context
   * @param o       the object to be converted
   * @return the converted String
   */
  public String convertToString(Map context, Object o) {
    
    Date date = (Date) o;
    String formatedDate = DateUtil.dateFormater(date, getDatePattern());
    return formatedDate;
  }
  
  private String getDatePattern() {
    
    ResourceBundle bundle = ResourceBundle.getBundle("package", ActionContext.getContext().getLocale());
    String pattern = bundle.getString("text.date.format");
    //LOG.info("current date pattern is:" + pattern);
    return pattern;
  }
}

Please don't forget to add "xwork-conversion.properties" and "package.properties" at your source folder root.
"xwork-conversion.properties" content should be

java.util.Date = DateConverter


"package.properties" content should be
text.date.format=MM/dd/yyyy
or other format pattern for different locale. For example package_zh_TW.properties or package_ja_JP.properties.
With this DateConverter, you can see different Date conversion result for your locale setting.