Servlet listener (3): servlet listener

Source: Internet
Author: User

Servlet listener (3): servlet listener

1. What is a servlet listener?

Servlet listeners are also called web listeners. Is a special class in servlet. It can help developers monitor specific events in web applications. For example, creation and destruction of ServletContext, ServletSession, ServletRequest, and variable creation and destruction.

2 listener common usage

Generally, the Web Listener is used to do the following:

Count the number of online users by using HttpSessionLisener

Loading initialization information: Using ServletContextListener

Count website visits

Achieve access monitoring

3. Listener Classification

Based on servlet objects, listeners can be divided into three types: ServletContext, ServletSession, and ServletRequest.

4 listener Application

  4.1 ServletContex: create and destroy the built-in objects of the monitoring application.

When the web container is enabled, run the contextInitialized method. when the container is closed or restarted, run the contextDestroyed method.

Implementation Method: directly implement the ServletContextListener Interface

package com.learn;import javax.servlet.ServletContext;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import java.io.*;/** * Created by Administrator on 2017/09/23. */public class MyServletContextListener implements ServletContextListener {    @Override    public void contextInitialized(ServletContextEvent sce) {        System.out.println("Webapp initital.......");        ServletContext servletContext = sce.getServletContext();       InputStreamReader inputStreamReader = new InputStreamReader(servletContext.getResourceAsStream("/count/count.txt"));        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);        try {            int icount = Integer.parseInt(bufferedReader.readLine());            icount++;            servletContext.setAttribute("count",icount);            System.out.println("Webapp initital success");        } catch (IOException e) {            e.printStackTrace();        }    }    @Override    public void contextDestroyed(ServletContextEvent sce) {        System.out.println("webApp destroyed ........");        ServletContext servletContext = sce.getServletContext();        Integer count = (Integer) servletContext.getAttribute("count");        if(count != null){            count ++;            String filePath = servletContext.getRealPath("/count");            filePath = filePath+"/count.txt";            try {                PrintWriter printWriter = new PrintWriter(filePath);                printWriter.write(count);                printWriter.close();                System.out.println("webApp desdroyed success ");            } catch (FileNotFoundException e) {                e.printStackTrace();            }        }    }}

  4.2HttpSession monitoring: monitors the creation and destruction of built-in session objects.

When a new page is opened, a session is enabled and the sessionCreated method is executed. When the page is closed and the session expires, or the container is closed and destroyed, the sessionDestroyed method is executed.

Implementation Method: directly implement the HttpSessionListener interface:

Package com. learn; import javax. servlet. http. httpSession; import javax. servlet. http. httpSessionEvent; import javax. servlet. http. httpSessionListener;/*** Created by Administrator on login /09/23. */public class MySessionListener implements HttpSessionListener {@ Override public void sessionCreated (HttpSessionEvent se) {HttpSession session = se. getSession (); System. out. println ("new session, sessionId:" + session. getId () ;}@ Override public void sessionDestroyed (HttpSessionEvent se) {HttpSession session = se. getSession (); System. out. println ("Destroy session, sessionId:" + session. getId ());}}

  4.3ServletRequest monitoring: create and destroy the built-in objects in the monitoring request.

When a page is accessed, a request is sent and the requestInitialized method is executed. When the page is closed, the requestDestroyed method is executed.

Implementation Method to directly implement the ServletRequestListener interface:

  

Package com. learn; import javax. servlet. servletRequestEvent; import javax. servlet. servletRequestListener; import javax. servlet. http. httpServletRequest;/*** Created by Administrator on login /09/23. */public class MyRequestListener implements ServletRequestListener {@ Override public void requestDestroyed (ServletRequestEvent sre) {HttpServletRequest request = (HttpServletRequest) sre. getServletRequest ( ); Long date = System. currentTimeMillis ()-(Long) (request. getAttribute ("dateCreated"); System. out. println ("consumed time:" + date) ;}@ Override public void requestInitialized (ServletRequestEvent sre) {HttpServletRequest request = (HttpServletRequest) sre. getServletRequest (); String uri = request. getRequestURI (); uri = request. getQueryString () = null? Uri: (uri + "? "+ Request. getQueryString (); request. setAttribute ("dateCreated", System. currentTimeMillis (); System. out. println ("IP:" + request. getRemoteAddr () + "URI:" + uri );}}

5 listener web. xml configuration

    <listener>     <listener-class>com.learn.MyServletContextListener</listener-class>    </listener>
<listener> <listener-class>com.learn.MySessionListener</listener-class> </listener>
<listener> <listener-class>com.learn.MyRequestListener</listener-class> </listener>

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.