Reputation: 16041
I am developing a multilingual Struts2 application, and I have quite a few actions which are dealing with Calendar
properties. The default type conversion works most of the time, however in some locales I would like to change the default format used.
Specifically I would like to have the dates in English locale to follow the yyyy-MM-dd
format. However, this does not work (strangely yyyy-MM-dd HH:mm
works fine, but in this case I do not want to have a time part), as Struts2 expect dates in English locale to look different.
So, I would like to change the expected format of the conversion. I am looking for a sane solution for this. The options I have already tried:
StrutsTypeConverter
. This should work, but I could not inject the format specified in the package.properties
file into it.String
instead - works, but this is not a sane solution.How to fix the solution A? Or is there an alternative approach? Of course, if this can be done entirely in configuration, that would be the best.
Upvotes: 3
Views: 1134
Reputation: 16041
Okay, I found a solution for my problem at hand, still, I think this could done in a saner way. Anyway, I am posting my own type converter:
public class DateConverter extends StrutsTypeConverter {
private DateFormat dateFormat;
{
ActionContext ctx = ActionContext.getContext();
ActionSupport action = (ActionSupport) ctx.getActionInvocation().getAction();
String formatString = action.getText("dateformat.ui");
dateFormat = new SimpleDateFormat(formatString);
}
public Object convertFromString(Map context, String[] values, Class toClass) {
String input = values[0];
try {
Date date = dateFormat.parse(input);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal;
} catch (ParseException e) {
return null;
}
}
public String convertToString(Map context, Object object) {
Calendar cal = (Calendar) object;
return dateFormat.format(cal.getTime());
}
}
I removed the non-essential parts of the code, but this is a working solution.
Upvotes: 2