Servlet Context Listener:
Global monitoring of an application is enabled as the application starts and disappears as the application disappears. There are two main methods:
ContextDestroyed (Servlet Context Event) is called when the application is closed
ContextInitialized (Servlet Context Event) is called when the application starts.
This listener is mainly used for some work to be completed as the application starts, that is, what many people say I want to do during the container and startup. Generally, it initializes the "global variables", such
- public void contextInitialized(ServletContextEvent event){
- ServletContex sc = event.getServletContext();
- sc.setAttribute(name,value);
- }
In the future, you can get servlet Context () in any servlet (). getAttribute (name); I like to use it for daemon, that is, to implement a Timer in the contextInitialized (Servlet ContextEvent event) method, then let the application make the Timer work at each startup:
Program code:
- Public void contextInitialized (ServletContextEvent event ){
- Timer=NewTimer ();
- Timer. schedule (new TimerTask (){
- Public void run (){
- // Do any things
- }
- }, 0, time interval );
- }
Some people say that Timer can only specify how long it takes to do things or when it takes to do things from now on, so how do I do a job on the first day of every month or at 12 o'clock every day?
You only need to set an interval and then judge whether the time period is the same. For example, if you do this on the first day of every month, you can set the interval to a day, that is, a cycle of 24 hours, then, judge the Date new Date () in the run method (). getDate () = 1. if it is 12 o'clock every day, set the time interval to hour, and then judge new Date () in run (). getHour () = 12. Just do something again.
Servlet Context AttributeListener:
This listener monitors events of Servlet Context objects in setAttribute () and removeAttribute (). Note that a "global variable" is being added (set for the first time ), replace (re-assign values to existing variables) and remove.
- Servlet sharing links in sessions
- Configure the Servlet Development Environment
- Future Response Servlet features
- Tomcat Java Servlet Engine Security Settings
- Jetty-Additional Servlet container Functions