servlet listener function explanation and code example

servlet listener function explanation and code example


The function of the listener is very powerful, but some junior engineers often ignore her,


soThere are also some listener interfaces that are not analyzed because they are not frequently used, such as session binding passivation activation, etc.):
1. Application monitoring is generally used to start timed tasks, initialize data, and load configuration files.
2.Monitoring - generally used to count the number of online people, etc.
3.

actions
1. Monitoring of
  application The application will only appear once in our server, when the project is started, then At this time, we wonder if we can add a monitor to him, so that we can handle some of our own things when the project starts. For example, when the project starts, we initialize the data and start some timed tasks, so that we don't have to worry about these. Function, because when the project starts, it has already helped us to complete the
   general listener is a common class and then implements a section of the listener interface, then let's write a case where the project starts and listens to the application.

Listener code
public class ContextLinstener implements ServletContextListener{

	@Override
	public void contextInitialized(ServletContextEvent sce) {//The method is triggered when the initialization project starts the application and generates
		System.out.println("====Start initialization----districts and counties---data======");
		CacheData.getCitys();//There is a static f method in the implementation class
		System.out.println("==========Initialize data----districts and counties---end, start initializing province and city data==========");
		CacheData.getProvinces();
		System.out.println("============Initialization data----province and city---end========");
		// start the task
		System.out.println("============Start timed task to read user's birthday data==========");
		TimeTask.timer4();//Call the timed task
	}
	@Override
	public void contextDestroyed(ServletContextEvent sce) {//关闭
		// TODO Auto-generated method stub
		// Triggered when the project is closed
	}
}

Code in the CacheData class

public class CacheData {
	public static List<CityModel> cms=new ArrayList<>();
	//Static variables are global, just write CacheData.cms when using static cached data
	public static List<ProvinceModel> pms=new ArrayList<>();
	
	public static void getCitys(){
		CityService cs=new CityService();
		cms=cs.doGetCitys();
		System.out.println("Total Districts and Counties"+cms.size()+"Data");
	}
    public static void getProvinces(){
    	ProvinceService ps=new ProvinceService();
    	pms=ps.doGetProvinces();
    	System.out.println("Total province and city"+pms.size()+"Data");
	}
}


The code inside the TimeTask class
public class TimeTask {
	    public static void main(String[] args) {  
	        // timer1 ();  
	        // timer2 ();  
	        //timer3();  
	        timer4 ();  
	    }  
	    // The first method: set the specified task task to execute schedule(TimerTask task, Date time) at the specified time  
	    public static void timer1() {  
	        Timer timer = new Timer ();  
	        timer.schedule(new TimerTask() {  
	            public void run() {  
	                System.out.println("-------Set the task to be specified-------");  
	            }  
	        }, 2000);// Set the specified time time, here is 2000 milliseconds  
	    }  
	  
	    // The second method: set the specified task task to execute the fixed delay peroid after the specified delay delay  
	    // schedule(TimerTask task, long delay, long period)  
	    public static void timer2() {  
	        Timer timer = new Timer ();  
	        timer.schedule(new TimerTask() {  
	            public void run() {  
	                System.out.println("-------Set the task to be specified-------");  
	            }  
	        }, 1000, 1000);  
	    }  
	  
	    // The third method: set the specified task task to execute the fixed frequency peroid after the specified delay delay.  
	    // scheduleAtFixedRate(TimerTask task, long delay, long period)  
	    public static void timer3() {  
	        Timer timer = new Timer ();  
	        timer.scheduleAtFixedRate(new TimerTask() {  
	            public void run() {  
	                System.out.println("-------Set the task to be specified-------");  
	            }  
	        }, 1000, 2000);  
	    }  
	     
	    // The fourth method: Schedule the specified task task to start at the specified time firstTime for repeated fixed rate period execution.  
	    // Timer.scheduleAtFixedRate(TimerTask task,Date firstTime,long period)  
	    public static void timer4() {  
	        Calendar calendar = Calendar.getInstance();  
	        calendar.set(Calendar.HOUR_OF_DAY, 16); // control hour  
	        calendar.set(Calendar.MINUTE, 9); // control minute  
	        calendar.set(Calendar.SECOND, 0); // control seconds  
	  
	        Date time = calendar.getTime(); // Get the time to execute the task, here is 1 o'clock today
	  
	       // System.out.println(time);
	        Timer timer = new Timer ();  
	        timer.scheduleAtFixedRate(new TimerTask() {  
	            public void run() {  
	                System.out.println("-------Start running batches, query the person who has a birthday today-------");  
	                //Run the batch to find out who has the birthday today  
	                //Send text or email
	            }  
	        }, time, 1000 * 60 * 60 * 24);// This setting will delay the fixed execution every day  
	    }  
	}  



The second type of listener session listener
We all know that the session will be generated when the user accesses, so at this time we write a session listener as long as there is a user access to know, this time we record it in the applicationcontest, when the saeeion is out of date, then Just subtract
the data we just recorded and the

session listener code is as follows

public class SessionLinstener implements HttpSessionListener {

	//The interface to implement session monitoring can only be triggered when there is a user access to generate a session //sessionCreated
    public void sessionCreated(HttpSessionEvent se) {
        // TODO Auto-generated method stub
    	System.out.println("session has been created");
    	ServletContext context = se.getSession().getServletContext();
        Integer count = (Integer) context.getAttribute("peopleOnline");
        if (count == null) {
            count = 1;
        } else {
            count++;
        }
        context.setAttribute("peopleOnline", count);
    }
	/**
     * @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
     */
    public void sessionDestroyed(HttpSessionEvent se) {
        // TODO Auto-generated method stub
    	 System.out.println("session is being destroyed");
    	 ServletContext context = se.getSession().getServletContext();
         Integer count = (Integer) context.getAttribute("peopleOnline");
         count--;
         context.setAttribute("peopleOnline", count);
    }
}

//Then how to print or display the online user information we recorded?
//You can write the current online number in jsp as: ${applicationScope.peopleOnline }


The third type of monitoring can be strong until the creation and destruction of requests. What is a request is that any request for a user to visit our website is a request, then we can use this feature to record the traffic of our website. How is
the specific code implemented? Woolen cloth?
public class RequestLinstener implements ServletRequestListener {

	/**
     * @see ServletRequestListener#requestInitialized(ServletRequestEvent)
     */
 //Similarly, this method can only be triggered when we implement the ServletRequestListener interface when there is a request
    public void requestInitialized(ServletRequestEvent sre) {
        // TODO Auto-generated method stub
    	System.out.println("request was created");
    	//Statistics of website traffic
    	ServletContext context = sre.getServletRequest().getServletContext();
        Integer count = (Integer) context.getAttribute("requestCount");
        if (count == null) {
            count = 1;
        } else {
            count++;
        }
        context.setAttribute("requestCount", count);
    }
	/**
     * @see ServletRequestListener#requestDestroyed(ServletRequestEvent)
     */
    public void requestDestroyed(ServletRequestEvent sre) {
        // TODO Auto-generated method stub
    	System.out.println("request is destroying");
    }
}
So how do I display this data on the page?
Visits: ${applicationScope.requestCount }


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326391774&siteId=291194637