Functions and usage of listener in web. xml

Source: Internet
Author: User

1. WebContextLoaderListenerListener
It can capture the start and stop of the server, and perform corresponding operations in the Start and Stop triggers!
It can be used only after being configured in web. xml.

II. The following are some listener knowledge collected.
Example 1
The listener goes online and exits to display online users.

1. log on to the Login. jsp page.

<% @ Page pageEncoding = "gb2312" contentType = "text/html; charset = gb2312" %>
<%
Session = request. getSession (false );
If (session! = Null) session. invalidate ();
%>
<Html>
<Head> <title> <Body>
<Form action = "isOnline. jsp" method = "post">
Username: <input type = "text" name = "uName"/>
<Input type = "submit" value = "online">
</Form>
</Body>
</Html>

2. The control page (just to illustrate the listener problem, so it's easy...) isOnline. jsp

<% @ Page pageEncoding = "gb2312" contentType = "text/html; charset = gb2312" %>
<Html>
<Head> <title> <Body>
<%
Session = request. getSession ();
Session. setAttribute ("userName", request. getParameter ("uName "));
Response. sendRedirect ("showOnline. jsp ");
%>
</Body>
</Html>

3. The showOnline. jsp page is displayed.

<% @ Page pageEncoding = "gb2312" contentType = "text/html; charset = gb2312" import = "java. util. ArrayList" %>
<Html>
<Head> <title> <Body>
<%
ArrayList showList = (ArrayList) (getServletContext (). getAttribute ("list "));
Out. print ("online users" + showList. size () + "<br> ");
For (int I = 0; I <showList. size (); I ++ ){
Out. print (showList. get (I) + "online" + "<br> ");
}
%>
<Br>
<A href = "Login. jsp"> exit </a>
</Body>
</Html>

4. Configure web. xml on the page

<? Xml version = "1.0" encoding = "gb2312"?>
<! DOCTYPE web-app
PUBLIC "-// Sun Microsystems, Inc. // DTD
Web Application 2.3 // EN"
Http://java.sun.com/dtd/web-app_2_3.dtd>
<Web-app>
<Listener>
<Listener-class> org. xiosu. listener. onlineListener </listener-class>
</Listener>
</Web-app>

5. Listener onlineListener. java

Package org. xiosu. listener;

Import java. util. ArrayList;
Import javax. servlet. ServletContext;
Import javax. servlet. http. HttpSessionAttributeListEner;
Import javax. servlet. http. HttpSessionBindingEvent;
Import javax. servlet. http. HttpSessionEvent;
Import javax. servlet. http. HttpSessionListener;

Public class onlineListener implements HttpSessionListener,
HttpSessionAttributeListEner {
// Parameters
ServletContext SC;
ArrayList list = new ArrayList ();
// This operation is triggered when a new session is created.
Public void sessionCreated (HttpSessionEvent se ){
SC = se. getSession (). getServletContext ();
System. out. println ("Create a session ");
}
// This operation is triggered when a session is destroyed.
Public void sessionDestroyed (HttpSessionEvent se ){
System. out. println ("destroy a session ");
If (! List. isEmpty ()){
List. remove (String) se. getSession (). getAttribute ("userName "));
SC. setAttribute ("list", list );
}
}
// This operation is triggered when an object is added to the session. An object is added to the list.
Public void attributeAdded (HttpSessionBindingEvent sbe ){
List. add (String) sbe. getValue ());
SC. setAttribute ("list", list );
}
// This operation is triggered when you modify or delete an object added to a session.
Public void attributeRemoved (HttpSessionBindingEvent arg0 ){
}
Public void attributeReplaced (HttpSessionBindingEvent arg0 ){
}
}

Note: In this example, only the listener is briefly introduced and security settings are not performed.

A Listener is also called a Listener. It is a Servlet Listener that can listen to client requests and server operations. Through the listener, some operations can be automatically triggered, such as the number of online users. When an HttpSession is added, sessionCreated (HttpSessionEvent
Se) method.
You can add 1 to the number of online users. Common listening interfaces include the following:
ServletContextAttributeLIstener monitors operations on the attributes of ServletContext, such as adding, deleting, and modifying attributes.
ServletContextListener listens to ServletContext. When a ServletContext is created, contextInitialized (ServletContextEvent
Sce) method. When ServletContext is destroyed, contextDestroyed (ServletContextEventSce) method.
HttpSessionListener listens for HttpSession operations. When a Session is createdCreated (HttpSessionEvent
Se) method. When a Session is destroyed, sessionDestroyed is triggered.(HttpSessionEventSe) method.
HttpSessionAttributeListListener listens to the attribute operations in HttpSession. When an attribute is added to a Session, attributeAdded (HttpSessionBindingEvent
Se)Method; When a Session deletes an attribute, attributeRemoved (HttpSessionBindingEvent
Se) method. When the Session attribute is reset, attributeReplaced (HttpSessionBindingEventSe)Method.
Example: start with the server
<Web-app>

Com. tb. listener. CountStartListener

Package com. tb. listener;
Import javax. servlet. ServletContextEvent;
Import javax. servlet. ServletContextListener;
Import javax. servlet. http. HttpServlet;
Import com. tb. timertask. DoCountTask;
Public class CountStartListener extends HttpServlet implements ServletContextListener
{
Private static final long serialVersionUID = 1824920962239905170L;
Public CountStartListener ()
{
// TODO Auto-generated constructor stub
}
Public void contextDestroyed (ServletContextEvent arg0)
{
// TODO Auto-generated method stub
}
Public void contextInitialized (ServletContextEvent arg0)
{
DoCountTask. dotask ();
}
}

Overview:

Servlet listeners are used to listen for important events. Listener objects can be processed before and after events occur.

Interface:

Currently, Servlet2.4 and JSP2.0 have a total of eight listener interfaces and six Event classes, of which HttpSessionAttributeListEner and

HttpSessionBindingListenBoth er use HttpSessionBindingEvent; HttpSessionListener and HttpSessionActivationLisTener uses HttpSessionEvent. The events corresponding to other Listener are as follows:

Listener Interface

Event class

ServletContextListener

ServletContextEvent

ServletContextAttributeLIstener

ServletContextAttributeEVent

HttpSessionListener

HttpSessionEvent

HttpSessionActivationLisTener

HttpSessionAttributeListEner

HttpSessionBindingEvent

HttpSessionBindingListenEr

ServletRequestListener

ServletRequestEvent

ServletRequestAttributeLIstener

ServletRequestAttributeEVent

Introduction:

A listener Interface related to ServletContext

Additional knowledge:

Through the instance of ServletContext, you can access the Global Object of the application and the variables in the initialization phase.

In the JSP file, the application is an instance of ServletContext, which is created by default by the JSP Container. Call the getServletContext () method in Servlet to obtain the instance of ServletContext.

Note:

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

<Context-param>

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

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

</Context-param>

When the container starts, an Application-range object will be created. To obtain this variable in the JSP webpage:

String name = (String) application. getInitParameter ("Name ");

Or when using EL:

$ {InitPara. name}

In Servlet, the method for obtaining the Name value is as follows:

String name = (String) ServletContext. getInitParameter ("Name ");

1. ServletContextListener:

The listener class needs to implement the javax. servlet. ServletContextListener interface.

ServletContextListener is the listener of ServletContext. If ServletContext changes, for example, ServletContext is created when the server is started, ServletContext will be destroyed when the server is closed.

Method of the ServletContextListener interface:

Void contextInitialized (ServletContextEvent sce)

The notification is for an accepted object. The application has been loaded and initialized.

Void contextDestroyed (ServletContextEvent sce)

The notification is receiving the object, and the application has been loaded.

Methods In ServletContextEvent:

Servletcontext getservletcontext ()

Retrieve the servletcontext object

2. servletcontextattributelIstener: Used to listen for events that change web application attributes, including adding, deleting, and modifying attributes. The Listener class must implement javax. servlet. servletcontextattributel.Istener interface.

ServletcontextattributelIstener interface method:

Void attributeadded (servletcontextattributeeVent scab)

If an object is added to the application scope, the object to be listened to will be notified.

Void attributeremoved (servletcontextattributeeVent scab)

If an object is removed from the application range, the notification is sent to the object being listened.

Void attributereplaced (servletcontextattributeeVent scab)

If an object in the application range replaces another object, the notification is listening to the object.

ServletcontextattributeeMethods in vent:

Java. Lang. String getname ()

Return attribute name

Java. Lang. Object getvalue ()

Return Attribute Value

2. http session listening Interfaces

1. HttpSessionBindingListenEr interface

Note: HttpSessionBindingListenThe er interface is the only Listener that does not need to be set in web. xml.

When our class implements HttpSessionBindingListenAfter the er interface, as long as the object is added to the Session range (that is, when the setAttribute method of the HttpSession object is called) or, when the removeAttribute method of the HttpSession object is called or the Session Time out, the container automatically calls the following two methods:

Void valueBound (HttpSessionBindingEvent event)

Void valueUnbound (HttpSessionBindingEvent event)

Thinking: how can we record the customer logon logs of a website and count the number of online users?

2. HttpSessionAttributeListEner Interface

HttpSessionAttributeListListener listens to the attribute operations in HttpSession.

When an attribute is added to a Session, the attributeAdded (HttpSessionBindingEvent se) method is triggered. When an attribute is deleted in the Session, the attributeRemoved (HttpSessionBindingEvent se) method is triggered; when the Session attribute is reset, The attributeReplaced (HttpSessionBindingEvent se) method is triggered. This is different from ServletContextAttributeL.Istener is similar.

3. httpsessionlistener Interface

Httpsessionlistener listens for httpsession operations. When a session is created, the session created (httpsessionevent SE) method is activated. When a session is destroyed, the sessiondestroyed (httpsessionevent SE) method is activated.

4. httpsessionactivationlisTener Interface

It is mainly used when the same session is transferred to different JVMs.

Iv. servletrequest listener Interface

1. servletrequestlistener Interface

Similar to the servletcontextlistener interface, servletcontext is changed to servletrequest.

2. servletrequestattributelIstener Interface

Similar to the servletcontextlistener interface, servletcontext is changed to servletrequest.

Some listener can be used to count the number of online users and visits of the website. As follows:

When the server is started (the servletcontextlistener listener contextinitialized method is implemented), the database is read, and a counting variable is saved within the application range.

When the session is created (the sessioncreated method of the httpsessionlistener listener is implemented), add 1 to the read count variable and save it again.

When the server is shut down (the contextdestroyed method of the servletcontextlistener listener is implemented), the database is updated.

From: http://www.blogjava.net/wx886104/archive/2010/06/01/322419.html

Http://hht83.blog.163.com/blog/static/44037112008324232278/

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.