How to delegate Map data structure to helper Class?
I have a Servlet where i use Map<Integer, String>
for month, day and year to get displayed in Select tag
with help of JSTL tag.
Like for example in a Servlet Code:
// Storing month in key-value pair
Map<Integer, String> months = new LinkedHashM开发者_Python百科ap<Integer,String>();
months.put(1, new String("Jan"));
months.put(2, new String("Feb"));
months.put(3, new String("Mar"));
months.put(4, new String("Apr"));
...
// Putting month in request scope to be accessed in JSP
request.setAttribute("months", months);
But, I want to write Map data structure code in other Helper class
and call it in Servlet so that my Servlet becomes less tedious
Question:
- How to delegate to helper class/method?
- How to call it in request scope in Servlet?
Simply:
Map<Integer, String> months = new Helper().months();
Depending on your needs you can implement it also as a static method. Using DI using normal method is more approriate (most of the time).
There's no need to hard core the months in the method. SimpleDateFormat can handle this. (It could be a bit nicer using joda time instead of the GregorianCalendar.)
public static Map<Integer, String> months() {
Map<Integer, String> months = new HashMap<Integer, String>();
for(int i=0;i<12;i++){
GregorianCalendar cal = new GregorianCalendar(2000, i, 1);
String month = new SimpleDateFormat("MMM", Locale.ENGLISH).format(cal.getTime());
months.put(i + 1, month);
}
return months;
}
Request scope: Your servlet is called for every request. As long as you're adding the month as an attribute to the request everything should be fine. There's actually no need to create the map for every request. Months don't change that much. You should store the map in the application context at start up.
I'm not sure If I followed you correctly but here it goes -
you can write a class say Helper
and can have a static method in it say getMonths
which will return this Map. Like -
public class Helper {
private Helper(){ }
private static Map<Integer, String> months = new LinkedHashMap<Integer, String>();
static{
months.put(1, "Jan");
months.put(2, "Feb");
months.put(3, "Mar");
months.put(4, "Apr");
...
}
public static Map<Integer, String> getMonths(){
return months;
}
}
and you can call this method from your servlet like -
Map<Integer, String> months = Helper.getMonths();
since this Map is constant but mutable, you can use ImmutableMap for this purpose from Guava.
Not quite sure, but can:
String[] months = DateFormatSymbols.getInstance().getMonths();
Method implementation:
public static Map<Integer, String> months() {
Map<Integer, String> months = new HashMap<Integer, String>();
String[] instance = DateFormatSymbols.getInstance(Locale.ENGLISH).getShortMonths();
for (int i = 0; i < instance.length; i++) {
months.put(i + 1, instance[i]);
}
return months;
}
精彩评论