The difference between Filter, Listener, and Servlet in web.xml

1. Servlet

Servlet is a basic server program, it comes from the interface Servlet, and there is a method service in the interface. An important implementation class of Servlet is the core of tomcat server, that is HttpServlet

HttpServlet has methods:

copy code

public abstract class HttpServlet extends GenericServlet
{
    private static final String METHOD_DELETE = "DELETE";
    private static final String METHOD_HEAD = "HEAD";
    private static final String METHOD_GET = "GET";
    private static final String METHOD_OPTIONS = "OPTIONS";
    private static final String METHOD_POST = "POST";
    private static final String METHOD_PUT = "PUT";
    private static final String METHOD_TRACE = "TRACE";

    private static final String HEADER_IFMODSINCE = "If-Modified-Since";
    private static final String HEADER_LASTMOD = "Last-Modified";
    
    private static final String LSTRING_FILE =
        "javax.servlet.http.LocalStrings";
    private static ResourceBundle lStrings =
        ResourceBundle.getBundle(LSTRING_FILE);
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    protected void doHead(HttpServletRequest req, HttpServletResponse resp)
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    protected void doPut(HttpServletRequest req, HttpServletResponse resp)
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
    protected void doOptions(HttpServletRequest req, HttpServletResponse resp)
    protected void doTrace(HttpServletRequest req, HttpServletResponse resp)
}

copy code

  Several do methods are the core, all client requests are ultimately processed through these methods of Servlet (unless intercepted by filters)

  

2. Listener

Listener is a listener for monitoring servlets. It is based on the observer pattern. Its core interface is ServletContextListener, which inherits from EventListener.

There are the following methods:

  public void contextInitialized(ServletContextEvent sce)

  public void contextDestroyed(ServletContextEvent sce)

The ServletContextEvent inherits from the java.util.EventSource class, which passes an event source in the constructor. The ServletContext can be obtained through the getServletContext method, and the ServletContext is the event source. (A simple Listener is only used to execute some statements when starting the server, then its Source is an ApplicationContextFacade, appearance mode, and the core is the context of the entire web program)

  The built-in listener can be used to monitor attribute changes, session creation, etc. Generally speaking, it is used to monitor servlets. Servlet listeners are used to monitor the occurrence of some important events. The listener object can do some necessary things before and after the occurrence of the event. processing.

  At present, Servlet2.4 and JSP2.0 have a total of 8 listener interfaces and 6 Event classes, of which HttpSessionAttributeListener and HttpSessionBindingListener both use HttpSessionBindingEvent; HttpSessionListener and HttpSessionActivationListener both use HttpSessionEvent; the events corresponding to other Listeners are as follows:

Listener interface

Event class

ServletContextListener

ServletContextEvent

ServletContextAttributeListener

ServletContextAttributeEvent

HttpSessionListener

HttpSessionEvent

HttpSessionActivationListener

HttpSessionAttributeListener

HttpSessionBindingEvent

HttpSessionBindingListener

ServletRequestListener

ServletRequestEvent

ServletRequestAttributeListener

ServletRequestAttributeEvent

  

  Introduced separately:

  1. ServletContext related listening interface

  Supplementary knowledge:

  Instances of ServletContext can access the application's global objects and variables in the initialization phase.

  In a JSP file, application is an instance of ServletContext, which is created by default by the JSP container. Call the getServletContext() method in the servlet to get the instance of ServletContext.

  Notice:

  The global object is the Application scope object. The variables in the initialization phase refer to the variables set through the <context-param> element in web.xml, and its scope is also the Application scope, for example:

  <context-param>

  <param-name>Name</param-name>

  <param-value>browser</param-value>

  </context-param>

  When the container starts, an object of the Application scope will be created. To obtain this variable in the JSP web page:

  String name = (String)application.getInitParameter("Name");
  or when using EL:
  ${initPara.name}
  If it is in a Servlet, get the value of Name:
  String name = (String)ServletContext.getInitParameter("Name" );
  1.ServletContextListener:
  Used to monitor the events of WEB application startup and destruction, the listener class needs to implement the javax.servlet.ServletContextListener interface.
  ServletContextListener is the listener of ServletContext. If the ServletContext changes, for example, the ServletContext is created when the server starts, and the ServletContext will be destroyed when the server shuts down.
  Methods of the ServletContextListener interface:
  void contextInitialized(ServletContextEvent sce)
  informs the receiving object that the application has been loaded and initialized.
  void contextDestroyed(ServletContextEvent sce)
  informs the receiving object that the application has been loaded.
  Methods in ServletContextEvent:
  ServletContext getServletContext()  
  Obtain ServletContext object
  2.ServletContextAttributeListener: used to monitor the events of WEB application attribute change, including: adding attributes, deleting attributes, modifying attributes, the listener class needs to implement the javax.servlet.ServletContextAttributeListener interface.
  ServletContextAttributeListener interface method:
  void attributeAdded(ServletContextAttributeEvent scab)
  If an object is added to the scope of Application, notify the listening object
  void attributeRemoved(ServletContextAttributeEvent scab)
  If an object is removed from the Application scope, notify the listening object
  void attributeReplaced(ServletContextAttributeEvent scab)
  If in the scope of Application, an object replaces another object, notify the listening object
  . The method in ServletContextAttributeEvent:
  java.lang.String getName()
  returns the name of the attribute
  java.lang.Object getValue()
  returns the attribute's Value
  2. HttpSession related listening interface 1. HttpSessionBindingListener
  interface
  Note: The HttpSessionBindingListener interface is the only Listener that does not need to be set in web.xml.
  After our class implements the HttpSessionBindingListener interface, as long as the object is added to the Session scope (that is, when the setAttribute method of the HttpSession object is called) or removed from the Session scope ( That is, when the removeAttribute method of the HttpSession object is called or when the Session Time out), the container will automatically call the following two methods:
  void valueBound(HttpSessionBindingEvent event)
  void valueUnbound(HttpSessionBindingEvent event)
  Thinking: How to realize the record of the website's customer login log , Count the number of people online?
  2.HttpSessionAttributeListener interface
  HttpSessionAttributeListener monitors the operation of attributes in HttpSession.
  When an attribute is added in the Session, the attributeAdded(HttpSessionBindingEvent se) method is activated; when an attribute is deleted in the Session, the attributeRemoved(HttpSessionBindingEvent se) method is activated; when the Session attribute is reset, the attributeReplaced(HttpSessionBindingEvent se) method is activated. This is similar to ServletContextAttributeListener.
  3.HttpSessionListener interface
  HttpSessionListener monitors the operation of HttpSession. When a Session is created, the session Created (HttpSessionEvent se) method is fired; when a Session is destroyed, the sessionDestroyed (HttpSessionEvent se) method is fired.
  4. The HttpSessionActivationListener interface
  is mainly used when the same Session is transferred to different JVMs.
  4. ServletRequest monitoring interface
  1. ServletRequestListener
  interface Similar to the ServletContextListener interface, here is changed from ServletContext to ServletRequest 2. ServletRequestAttributeListener
  interface
  Similar to the ServletContextListener interface, here is changed from ServletContext to ServletRequest
  Some listeners can be used to count the number of people online and the number of visits to the website. As follows:
  When the server starts (implementing the contextInitialized method of the ServletContextListener listener), read the database and save it as a count variable in the application scope.
  When the session is created (implement the HttpSessionListener listener sessionCreated method), read the count variable and add 1 and reset it. Save
  When the server shuts down (implementing the ServletContextListener listener contextDestroyed method), update the database.

3. Filter

Filter is a filter, used to filter requests to servlets, it allows users to change a request and modify a response. Filter is not a servlet, it cannot generate a response, it can preprocess a request before a request reaches the servlet, or Handle the response when leaving the servlet. In other words, filter is actually a "servlet chaining" (servlet chain). 

A Filter includes:

1), intercepted before the servlet is called;

2), check the servlet request before the servlet is called;

3), modify the request header and request data as needed;

4), modify the response header and response data as needed;

5), intercepted after the servlet is called.

The server only calls the setFilterConfig method once to prepare for filter processing; calls the doFilter method multiple times to process different requests. The FilterConfig interface has a method to find the filter name and initialization parameter information. The server can set FilterConfig to be empty to indicate that the filter has terminated.

Each filter gets the current request and response from the doFilter() method. In this method, you can perform any operations on the request and response (including collecting data, packaging data, etc.). The filter calls the chain.doFilter() method Pass control to the next filter. A filter ends in the doFilter() method. If a filter wants to stop request processing and gain full control over the response, it can not call the next filter.

 

Among the three, Servlet and Filter can be configured with mapping, that is, for which address requests use these Servlets or Filters, and Listener judges under what circumstances to call this Listener according to the implementation interface. The basic Listener is only at startup. perform some tasks. If a request calls these three at the same time, the execution order is: Listener, Filter, Servlet.

Guess you like

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