The difference between Filter,listener,servlet in Web. xml

Source: Internet
Author: User
Tags tomcat server

First, the Servlet

A servlet is a basic service-side program that comes from an interface servlet and has a method service in the interface. One of the most important implementations of the servlet is the core of the Tomcat server, which is HttpServlet

HttpServlet There are methods:

 Public Abstract classHttpServletextendsgenericservlet{Private Static FinalString method_delete = "DELETE"; Private Static FinalString method_head = "HEAD"; Private Static FinalString method_get = "GET"; Private Static FinalString method_options = "OPTIONS"; Private Static FinalString method_post = "POST"; Private Static FinalString method_put = "PUT"; Private Static FinalString method_trace = "TRACE"; Private Static FinalString header_ifmodsince = "If-modified-since"; Private Static FinalString header_lastmod = "Last-modified"; Private Static FinalString lstring_file = "Javax.servlet.http.LocalStrings"; Private StaticResourceBundle lstrings =Resourcebundle.getbundle (Lstring_file); protected voiddoget (httpservletrequest req, HttpServletResponse resp)protected voidDohead (httpservletrequest req, HttpServletResponse resp)protected voidDoPost (httpservletrequest req, HttpServletResponse resp)protected voidDoPut (httpservletrequest req, HttpServletResponse resp)protected voidDoDelete (httpservletrequest req, HttpServletResponse resp)protected voiddooptions (httpservletrequest req, HttpServletResponse resp)protected voidDotrace (httpservletrequest req, HttpServletResponse resp)
}

Several do methods are core, and all client requests are ultimately handled by these methods of the servlet (unless blocked by the filter)

  

Second, Listener

Listener is the listener, which listens to the servlet, he is based on the observer pattern, and his core interface is Servletcontextlistener, inherited from EventListener.

The following methods are available:

public void contextinitialized (Servletcontextevent SCE)

public void contextdestroyed (Servletcontextevent SCE)

Where Servletcontextevent inherits from the Java.util.EventSource class, which passes an event source in the constructor method, which can be obtained by Getservletcontext method to obtain the Servletcontext,servletcontext as The event source. (Simply a simple listener, just to execute some statements when starting the server, his source is a applicationcontextfacade, the appearance mode, the core is the context of the entire Web program)

The built-in listener can be used to listen for property changes, session creation, and so on, generally used to listen to the servlet, the servlet listener is used to listen to the occurrence of some important events, listener objects can be done before, after the occurrence can do some necessary processing.

There are currently 8 listener interfaces and 6 event classes in Servlet2.4 and JSP2.0, where Httpsessionattributelistener and Httpsessionbindinglistener both use httpsessionbindingevent; Both Httpsessionlistener and Httpsessionactivationlistener use Httpsessionevent, and the remaining listener corresponding event is as follows:

Listener interface

Event class

Servletcontextlistener

Servletcontextevent

Servletcontextattributelistener

Servletcontextattributeevent

Httpsessionlistener

Httpsessionevent

Httpsessionactivationlistener

Httpsessionattributelistener

Httpsessionbindingevent

Httpsessionbindinglistener

Servletrequestlistener

Servletrequestevent

Servletrequestattributelistener

Servletrequestattributeevent

  

Introduced separately:

First, ServletContext related monitoring interface

Additional knowledge:

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

In the JSP file, application is an instance of ServletContext, created by default by the JSP container. The Getservletcontext () method is called in the Servlet to get an instance of ServletContext.

Attention:

The global object is the application scope object, and the variables in the initialization phase refer to the variables set by the <context-param> element in Web. XML, and its scope is also application range, for example:

<context-param>

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

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

</context-param>

When the container starts, a application-scoped object is created to get this variable in the JSP Web page:

String name = (string) application.getinitparameter ("name");
Or when using el:
${initpara.name}
If you are in a servlet, get the value method for name:
String name = (string) servletcontext.getinitparameter ("name");
1.ServletContextListener:
The listener class needs to implement the Javax.servlet.ServletContextListener interface to listen for events that the Web app launches and destroys.
Servletcontextlistener is a listener for ServletContext, if ServletContext changes, such as when the server is started ServletContext is created, the server shuts down ServletContext will be destroyed.
Servletcontextlistener interface Method:
void contextinitialized (Servletcontextevent SCE)
Notifies the object being accepted that the application has been loaded and initialized.
void contextdestroyed (Servletcontextevent SCE)
Notifies the object being accepted that the application has been loaded.
Methods in Servletcontextevent:
ServletContext Getservletcontext ()
Get ServletContext Object
2.ServletContextAttributeListener: Used to listen for changes in Web App properties, including: Adding Properties, deleting properties, modifying properties, The listener class needs to implement the Javax.servlet.ServletContextAttributeListener interface.
Servletcontextattributelistener interface Method:
void attributeadded (Servletcontextattributeevent scab)
Notifies an object that is listening if an object is added to the range of application
void attributeremoved (Servletcontextattributeevent scab)
Notifies an object that is listening if an object is removed from the application range
void attributereplaced (Servletcontextattributeevent scab)
Notifies an object that is listening when an object is substituted for another object in the range of application
Methods in Servletcontextattributeevent:
Java.lang.String GetName ()
Name of the callback property
Java.lang.Object GetValue ()
Value of the Callback property
Second, httpsession related monitoring interface
1.HttpSessionBindingListener interface
Note: The Httpsessionbindinglistener interface is the only listener that does not need to be set in Web. xml
When our class implements the Httpsessionbindinglistener interface, as long as the object joins the The session range (that is, when the setattribute method of the HttpSession object is called) or removed from the session range (that is, when the RemoveAttribute method of the HttpSession object is called or session time When it is out), the container automatically calls the following two methods, respectively:
void Valuebound (Httpsessionbindingevent event)
void Valueunbound (Httpsessionbindingevent event)
Thinking: How to realize the logging of the customer log on the website, statistics online number?
2.HttpSessionAttributeListener interface
Httpsessionattributelistener listens for properties in the httpsession operation.
When an attribute is added to the session, the attributeadded (httpsessionbindingevent se) method is fired; When a property is deleted at the session, the attributeremoved is fired ( Httpsessionbindingevent se) method, which fires the attributereplaced (httpsessionbindingevent se) method when the session property is reset. This is more like Servletcontextattributelistener.
3.HttpSessionListener interface
Httpsessionlistener Monitor the operation of the HttpSession. The session Created (Httpsessionevent se) method is fired when a session is created, and the sessiondestroyed (httpsessionevent se) method is fired when a session is destroyed.
4.HttpSessionActivationListener interface
Used primarily for the same session transfer to a different JVM.
Four, ServletRequest monitoring interface
1.ServletRequestListener interface
Similar to the Servletcontextlistener interface, this is changed from ServletContext to ServletRequest
2.ServletRequestAttributeListener interface
Similar to the Servletcontextlistener interface, this is changed from ServletContext to ServletRequest
Some listener can be used to count the number of online websites and visits. As follows:
When the server starts (implements the Servletcontextlistener listener Contextinitialized method), reads the database and saves it in the application range with a count variable
Session creation (implement Httpsessionlistener listener sessioncreated method), read count variable plus 1 and resave
When the server shuts down (implement the Servletcontextlistener listener Contextdestroyed method), update the database.

Third, Filter

Filter filters are used to filter the request to the servlet, which allows the user to change a request and modify a response. Filter is not a servlet, it cannot produce a response, it can preprocess the request before a request arrives at the servlet, or it can handle response when it leaves the servlet. In other words, filter is actually a "Servlet Chaining" (servlet chain).

A filter includes:

1), intercepted before the servlet is invoked;

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

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

4), modify response head and response data as needed;

5), intercepted after the servlet is invoked.

The server only calls the Setfilterconfig method one time to prepare filter processing, and calls the Dofilter method multiple times to handle different requests. The Filterconfig interface has methods to find the filter name and initialization parameter information. Server can set Filterconfig NULL to indicate that the filter has been terminated.

Each filter gets the current request and response from the Dofilter () method. In this method, you can do any action for request and response. (including collecting data, packing data, etc.). Filter calls the Chain.dofilter () method to give control to the next filter. A filter in DoFilter () Method ends. If a filter wants to stop the request processing and get full control of the response, it can not invoke the next filter.

Of these three, servlet and filter can be configured mapping, that is, for which address requests use these servlets or filter, and listener is based on the implementation of the interface to determine what the situation calls this listener, The basic listener only performs some tasks at startup. If a request is called at the same time to these three, then the order of execution is: Listener,filter,servlet.

http://blog.csdn.net/agileclipse/article/details/9014683

The difference between Filter,listener,servlet in Web. xml

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.