我在我自己的开源项目中是这么做的
用FILTER
在WEB.XML中你可以看到这样的配置
<filter-mapping>
<filter-name>MainFilter</filter-name>
<servlet-name>XXXservlet</servlet-name>
</filter-mapping>
<filter-mapping>
<filter-name>controlFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
MainFilter只做XXXservlet过来的request
controlFilter做所有的request
然后你自己实现一个FilterChain吧,第一步Filter什么(比如权限)
第二步Filter什么(比如日志)等等
至于初始化,用一个Listener搞定,例子如下:
public void contextInitialized(ServletContextEvent sce) {
//Servlet初始化,你尽管把系统启动时要加载的放在这里
BasicConfigurator.configure();
welcome();
logger.debug("contextInitialized");
}
//Notification that the servlet context is about to be shut down
public void contextDestroyed(ServletContextEvent sce) {
//这个是系统结束时的东东
leave();
logger.debug("contextDestroyed");
}
//Notification that a new attribute has been added to the servlet context
public void attributeAdded(ServletContextAttributeEvent scab) {
logger.debug("attributeAdded");
}
//Notification that an attribute has been removed from the servlet context
public void attributeRemoved(ServletContextAttributeEvent scab) {
logger.debug("attributeRemoved:"+scab.getName()+" : "+scab.getValue().toString());
}
//Notification that an attribute of the servlet context has been replaced
public void attributeReplaced(ServletContextAttributeEvent scab) {
logger.debug("attributeReplaced:"+scab.getName()+" : "+scab.getValue().toString());
}
//Notification that a session was created
public void sessionCreated(HttpSessionEvent se) {
logger.debug("sessionCreated");
}
//Notification that a session was invalidated
public void sessionDestroyed(HttpSessionEvent se) {
logger.debug("sessionDestroyed");
}
//Notification that a new attribute has been added to a session
public void attributeAdded(HttpSessionBindingEvent se) {
logger.debug("attributeAdded");
}
//Notification that an attribute has been removed from a session
public void attributeRemoved(HttpSessionBindingEvent se) {
logger.debug("attributeRemoved");
}
//Notification that an attribute of a session has been replaced
public void attributeReplaced(HttpSessionBindingEvent se) {
logger.debug("attributeReplaced");
}
你可以看到,你系统加载时可以做什么,系统结束时可以做什么,包括Session创建和销毁时可以做什么,好多的事情可以做哦
这些都是Servlet的标准,要更详细的信息不如去看看SUN的文档吧,希望对你有用。
:)