![]() 图 9 指定监听器的名字 |
![]() 图 10 选择监听器需要实现的事件接口 |
| 1. package bookstore.servlet; 2. … 3. import java.io.*; 4. import java.util.*; 5. import java.text.SimpleDateFormat; 6. 7. public class SrvStartListener 8. extends HttpServlet implements ServletContextListener 9. { 10. 11. public void contextInitialized(ServletContextEvent sce) 12. { 13. GregorianCalendar cal = new GregorianCalendar(); 14. int year = cal.get(Calendar.YEAR);//得到当前年份 15. int month = cal.get(Calendar.MONTH)+1;//得到当前月份 16. File file = new File("D:\\serverLog\\log_"+year+"_"+month+".xls"); 17. FileWriter fw = null; 18. try 19. { 20. //如果文件存在,日志追加到文件末尾,否则创建新的文件 21. fw = new FileWriter(file,true); 22. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 23. String starttime = sdf.format(new Date()); 24. fw.write("于"+starttime+"启动Web容器\n"); 25. } catch (IOException ex) 26. { 27. ex.printStackTrace(); 28. } finally 29. { 30. try 31. { 32. if (fw != null) 33. { 34. fw.close(); 35. } 36. } catch (IOException ex1) 37. { 38. ex1.printStackTrace(); 39. } 40. } 41. } 42. … 43. } |
| 2. <web-app> 3. … 4. <listener> 5. <listener-class>bookstore.servlet.SrvStartListener</listener-class> 6. </listener> 7. … 8. </web-app> |