Listener function and its use in Web. xml

Source: Internet
Author: User

I. Webcontextloaderlistener Monitoring class
It can catch the server start and stop, in the start and stop trigger inside the method to do the corresponding operation!
It must be configured in Web. XML to use the ability to configure the Listener class

Two. The following is a collection of some listener knowledge
A brief example
Monitor users on-line and exit, show online users

1. Landing Page login.jsp

<% @page pageencoding= "gb2312" contenttype= "text/html; charset=gb2312 "%>
<%
Session=request.getsession (FALSE);
if (session!=null) session.invalidate ();
%>
<body>
<form action= "isonline.jsp" method= "POST" >
Username:<input type= "text" name= "UName"/>
<input type= "Submit" value= "Online" >
</form>
</body>

2, control the page (just to illustrate the listener problem, so simple point ... ) isonline.jsp

<% @page pageencoding= "gb2312" contenttype= "text/html; charset=gb2312 "%>
<body>
<%
Session=request.getsession ();
Session.setattribute ("UserName", Request.getparameter ("UName"));
Response.sendredirect ("showonline.jsp");
%>
</body>


3. Display Page showonline.jsp

<% @page pageencoding= "gb2312" contenttype= "text/html; charset=gb2312 "import=" Java.util.ArrayList "%>
<body>
<%
ArrayList showlist= (ArrayList) (Getservletcontext (). getattribute ("list"));
Out.print ("Online Numbers" +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>

4. Configuration pageWeb.XML

<?XMLVersion= "1.0" encoding= "gb2312"?>
<! DOCTYPEWeb-app
Public "-//sun Microsystems, INC.//DTDWebApplication 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 {
Number of references
ServletContext SC;
ArrayList list = new ArrayList ();
This action is triggered when a new session is created
public void sessioncreated (Httpsessionevent se) {
Sc=se.getsession (). Getservletcontext ();
SYSTEM.OUT.PRINTLN ("new Session");
}
This action is triggered when a session is destroyed
public void sessiondestroyed (Httpsessionevent se) {
System.out.println ("Destroying a Session");
if (!list.isempty ()) {
List.remove (String) se.getsession (). getattribute ("UserName"));
Sc.setattribute ("list", list);
}
}
Trigger this action when adding an object to the session, adding an object to the list
public void attributeadded (Httpsessionbindingevent sbe) {
List.add (String) Sbe.getvalue ());
Sc.setattribute ("list", list);
}
Trigger this action when you change or delete an object in the session
public void attributeremoved (Httpsessionbindingevent arg0) {
}
public void attributereplaced (Httpsessionbindingevent arg0) {
}
}


Note: This example is simply a briefing listener and does not have security settings.

The listener, also known as listener, is the listener of the servlet, which listens to client requests, service-side operations, and so on. Through the listener, you can proactively motivate some operations, such as listening to the number of users online. When adding a httpsession, the sessioncreated is excited (httpsessionevent SE) method, so
will be able to add 1 to the online population. There are several listening interfaces that are used frequently:
ServletcontextattributelIstener listens to the operation of the ServletContext property, such as adding, deleting, and altering properties.
Servletcontextlistener Monitor ServletContext. When ServletContext is created, the contextinitialized is fired (servletcontexteventSCE) method, and when the ServletContext is destroyed, the contextdestroyed is fired (servletcontexteventSCE) method.
Httpsessionlistener Monitor the operation of the HttpSession. When a session is created, the session is firedCreated (httpsessioneventSE) method; When a session is destroyed, the sessiondestroyed is fired(httpsessioneventSE) method.
HttpsessionattributelistEner listens for properties in the httpsession operation. When you add a property to a session, the attributeadded is fired (httpsessionbindingeventSeWhen a property is deleted at the session, the attributeremoved is fired (httpsessionbindingeventSE) method, and when the session property is set again, the attributereplaced is fired (httpsessionbindingeventSeMethod.
Example: Starting with server
TheWeb-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:

The servlet listener is used to listen for important events, and listener objects can do the necessary things before and after they occur.

Interface:

For now, Servlet2.4 and JSP2.0 collectively have 8 listener interfaces and 6 event classes, HttpsessionattributelistEner and

Httpsessionbindinglistener both use httpsessionbindingevent; Httpsessionlistener and Httpsessionactivationlistener use Httpsessionevent, while the rest listener corresponding event such as the following:

Listener interface

Event class

Servletcontextlistener

Servletcontextevent

ServletcontextattributelIstener

ServletcontextattributeeVent

Httpsessionlistener

Httpsessionevent

HttpsessionactivationlisTener

HttpsessionattributelistEner

Httpsessionbindingevent

HttpsessionbindinglistenER

Servletrequestlistener

Servletrequestevent

ServletrequestattributelIstener

ServletrequestattributeeVent

Introduced separately:

A ServletContext related listening 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, such as:

<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, assuming that servletcontext changes, such as when the server is started, ServletContext is created, and 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: An event that listens for Web App property changes, including: Add, delete, change properties, The listener class needs toimplement the Javax.servlet.ServletContextAttributeL Istener interface.

ServletcontextattributelIstener interface method:

void attributeadded (servletcontextattributeevent scab)

What if there are objects to add? The range of application that informs the object being listened to

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 there is an object in place of an object in the range of application

ServletcontextattributeeMethods in vent:

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: Thehttpsessionbindinglisten ER interface is the only listener that does not need to be set in Web. xml

When our class implements the Httpsessionbindinglistener interface, only the object is added. 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 At the time of the Out), the container will voluntarily invoke the following two methods, respectively:

void Valuebound (Httpsessionbindingevent event)

void Valueunbound (Httpsessionbindingevent event)

Thinking: How to achieve Logging site customer log, statistics online number?

2.HttpSessionAttributeListEner interface

HttpsessionattributelistEner The operation to listen for properties in HttpSession.

When adding a property to the session, the attributeadded (httpsessionbindingevent se) method is fired, and 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 set again. This is similarto Servletcontextattributel Istener.

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 of the listener can be used to count the number of online visitors and visits. For example, the following:

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 save again

When server shuts down (implement Servletcontextlistener listener Contextdestroyed method), update the database


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

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

Listener function and its use 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.