Listener function and use __web in Web.xml

Source: Internet
Author: User
Tags joins log log stub

A. Webcontextloaderlistener Listening class
It can capture the server to start and stop, in the start and stop triggering inside the method to do the appropriate operation!
It must be configured in Web.xml to be used, and is to configure the Listener class

Two. The following are some of the listener knowledge gathered
Simple example of a
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" >
User name: <input type= "text" name= "UName"/>
<input type= "Submit" value= "Online" >
</form>
</body>

2, Control 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 number" +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 page Web.xml

<?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 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 ("Destroy a Session");
if (!list.isempty ()) {
List.remove ((String) se.getsession (). getattribute ("UserName"));
Sc.setattribute ("list", list);
}
}
This action is triggered when an object is added to the session, and an object is added to the list
public void attributeadded (Httpsessionbindingevent sbe) {
List.add ((String) sbe.getvalue ());
Sc.setattribute ("list", list);
}
Trigger this action when adding an object in the session is modified and deleted
public void attributeremoved (Httpsessionbindingevent arg0) {
}
public void attributereplaced (Httpsessionbindingevent arg0) {
}
}


Note: This example simply describes the listener and does not have security settings.

The listener, also called listener, is a servlet listener that listens to client requests, service-side operations, and so on. With listeners, you can automatically fire some actions, such as the number of users listening online. When a httpsession is added, the sessioncreated (httpsessionevent se) method is fired, so
You can add 1 to the online population. The following are several common listening interfaces:
Servletcontextattributelistener listens to operations on the ServletContext attribute, such as adding, deleting, and modifying attributes.
Servletcontextlistener Monitor ServletContext. When the ServletContext is created, the contextinitialized (Servletcontextevent SCE) method is fired, and when the ServletContext is destroyed, the contextdestroyed is fired ( Servletcontextevent sce) method.
Httpsessionlistener listens for httpsession operations. When a session is created, the session Created (Httpsessionevent se) method is fired, and the sessiondestroyed (httpsessionevent se) method is fired when a session is destroyed.
Httpsessionattributelistener the action to listen for properties in HttpSession. When an attribute is added to the session, the attributeadded (httpsessionbindingevent se) method is fired, and when a property is deleted in session, the attributeremoved is fired ( Httpsessionbindingevent se) method, which fires the attributereplaced (httpsessionbindingevent se) method when the session property is reset.
Example: Start with 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:

The servlet listener listens to the occurrence of important events, and the listener object can do the necessary processing before and after the event occurs.

Interface:

Currently there are 8 listener interfaces and 6 event classes for Servlet2.4 and JSP2.0, of which Httpsessionattributelistener and

Httpsessionbindinglistener all use httpsessionbindingevent; Httpsessionlistener and Httpsessionactivationlistener are all using Httpsessionevent; the rest listener the 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:

A ServletContext related listening interface

Supplementary knowledge:

An instance of ServletContext allows access to the global object of the application and the variables of the initialization phase.

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

Attention:

The global object is the application scope object, and the initialization stage variable refers to the Web.xml, which is defined by the <context-param> element, and its scope is application range, for example:

<context-param>

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

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

</context-param>

When the container is started, a application-scoped object is established to get the variable in the JSP Web page:

String name = (string) application.getinitparameter ("name");

Or when using el:

${initpara.name}

In the 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 monitor events for Web application startup and destruction.

Servletcontextlistener is a ServletContext listener, if servletcontext changes, such as when the server is started ServletContext is created and the server shuts down ServletContext will be destroyed.

Methods for Servletcontextlistener interfaces:

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 changes to Web application properties, including: Adding properties, deleting attributes, modifying properties, The listener class needs to implement the Javax.servlet.ServletContextAttributeListener interface.

Servletcontextattributelistener interface Method:

void attributeadded (Servletcontextattributeevent scab)

If an object joins the range of application, notify the object being listened to

void attributeremoved (Servletcontextattributeevent scab)

If an object is removed from the application range, notify the object being listened to

void attributereplaced (Servletcontextattributeevent scab)

When an object replaces another object in the range of application, notify the object being listened to

Methods in Servletcontextattributeevent:

Java.lang.String GetName ()

The name of the postback property

Java.lang.Object GetValue ()

The value of the postback property

Second, httpsession related listening interface

1.HttpSessionBindingListener interface

Note: The Httpsessionbindinglistener interface is the only one that does not need to be web.xml set listener

When our class implements the Httpsessionbindinglistener interface, as long as the object joins the Session scope (that is, when the setattribute method of the HttpSession object is invoked) or removed from the session scope (that is, when the RemoveAttribute method of the call HttpSession object is invoked or session time Out, the container automatically invokes the following two methods, respectively:

void Valuebound (Httpsessionbindingevent event)

void Valueunbound (Httpsessionbindingevent event)

Thinking: How to achieve the record site of the customer log log, statistics online number.

2.HttpSessionAttributeListener interface

Httpsessionattributelistener the action to listen for properties in HttpSession.

When an attribute is added to the session, the attributeadded (httpsessionbindingevent se) method is fired, and when a property is deleted in session, the attributeremoved is fired ( Httpsessionbindingevent se) method, which fires the attributereplaced (httpsessionbindingevent se) method when the session property is reset. This is similar to Servletcontextattributelistener.

3.HttpSessionListener interface

Httpsessionlistener listens for httpsession operations. When a session is created, the session Created (Httpsessionevent se) method is fired, and the sessiondestroyed (httpsessionevent se) method is fired when a session is destroyed.

4.HttpSessionActivationListener interface

Mainly for situations where the same session is transferred to a different JVM.

Four, ServletRequest listening 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 website and the amount of visitors. As follows:

When the server starts (implements the Servletcontextlistener listener Contextinitialized method), reads the database and saves it in application range with a count variable

Session creation (implement Httpsessionlistener listener sessioncreated method), read count variable plus 1 and save again

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


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

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

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.