我有一个 Servlet,我使用 Map<Integer, String>
月、日和年显示在 Select tag
中在 JSTL 标签的帮助下。
就像 Servlet 代码中的示例:
// Storing month in key-value pair
Map<Integer, String> months = new LinkedHashMap<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);
但是,我想在其他Helper class
中编写Map数据结构代码并在Servlet中调用它,这样我的Servlet变得不那么繁琐
问题:
- 如何委托(delegate)给辅助类/方法?
- 如何在Servlet的请求范围内调用它?
最佳答案
简单地说:
Map<Integer, String> months = new Helper().months();
根据您的需要,您也可以将其实现为静态方法。使用正常方法使用 DI 更为合适(大多数时候)。
无需对方法中的月份进行硬核处理。 SimpleDateFormat 可以处理这个问题。 (使用 joda 时间而不是 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;
}
请求范围:每个请求都会调用您的 servlet。只要您将月份作为属性添加到请求中,一切都应该没问题。实际上没有必要为每个请求创建 map 。几个月变化不大。您应该在启动时将 map 存储在应用程序上下文中。
关于java - 如何将Map数据结构委托(delegate)给辅助类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6148237/