The role of Web listeners

Source: Internet
Author: User
Tags sessions java web apache tomcat

The listener is a very important content in Java Web Development, and the knowledge involved can be referenced in the following diagram:

Web Listener

1 What is a Web listener.

Web listeners are special classes in a servlet that help developers listen to specific events in the Web, such as the creation and destruction of servletcontext,httpsession,servletrequest, the creation, destruction, and modification of variables. Can be added before and after some action to achieve monitoring.

2 Common uses of listeners

You typically use a Web listener to do the following:

Statistics online numbers, using Httpsessionlisener

Loading initialization information: using Servletcontextlistener

Statistics website Visit amount

Implementing Access Monitoring

3 Take a look at the creation of a listener and the execution process

First you need to create a listener to implement some kind of interface, such as I want to implement a monitoring of the number of online, you can create the following listener:

public class MyListener implements httpsessionlistener{
    private int usernumber = 0;
    public void sessioncreated (Httpsessionevent arg0) {
        usernumber++;
        Arg0.getsession (). setattribute ("Usernumber", Usernumber);
    public void sessiondestroyed (Httpsessionevent arg0) {
        usernumber--;
        Arg0.getsession (). setattribute ("Usernumber", Usernumber);
    }

Then configure the listener in Web.xml to add the following in Web-app:

  <listener>
      <listener-class>com.test.MyListener</listener-class>
  </listener>

Add number of visitors to the JSP:

<body>
    Online Number: <%=session.getattribute ("Usernumber")%><br/>
</body>

When I use my browser to access, the results are as follows:

When you open another browser access:

The number of online people is increased by opening another browser to access, equivalent to another session.

For the 3.0 version of the servlet, it also supports the use of annotations for configuration.

Then let's look at the listeners and the methods. Classification of listeners

1 divided by listening objects:

It can be divided into three different kinds of listening objects:

ServletContext monitoring: The corresponding monitoring application built-in object creation and destruction.

Executes the Contextinitialized method when the Web container is open, and executes the Contextdestroyed method when the container is closed or restarted.

Implementation: Direct implementation of the Servletcontextlistener interface:

public class Myservletcontextlistener implements servletcontextlistener{public
    void contextdestroyed ( Servletcontextevent SCE) {

    } public
    void contextinitialized (Servletcontextevent sce) {

    }
}

HttpSession monitoring: The corresponding monitoring session built-in object creation and destruction.

When a new page is opened, a session dialog is opened, the Sessioncreated method is executed, and the Sessiondestroyed method is executed when the page closes the sessions expire, or when the container closes the destroy.

Implementation: Direct implementation of the Httpsessionlistener interface:

public class Myhttpsessionlistener implements httpsessionlistener{public
    void sessioncreated (httpsessionevent arg0) {

    } public
    void sessiondestroyed (Httpsessionevent arg0) {

    }
}

ServletRequest monitoring: Create and destroy corresponding monitor request built-in objects.

When a page is accessed, a request is started, the Requestinitialized method is executed, and the Requestdestroyed method is executed when the page is closed.

Implementation, directly implement Servletrequestlistener interface:

public class Myservletrequestlistener implements servletrequestlistener{public
    void requestdestroyed ( Servletrequestevent arg0) {

    } public
    void requestinitialized (Servletrequestevent arg0) {

    }
}

2 According to the listening event Division:

2.1 The creation and destruction of the listener event itself: divided by object as above.

2.2 New, deleted, and modified listener properties:

The new, deleted, and modified listening properties are also divided into three types, respectively, for ServletContext, HttpSession, ServletRequest objects:

ServletContext, implement Servletcontextattributelistener interface:

The name of the property can be obtained by calling the Servletcontextattribtueevent GetName method.

public class Myservletcontextattrlistener implements servletcontextattributelistener{public

    void attributeadded (Servletcontextattributeevent hsbe) {
        System.out.println ("in ServletContext added:name =" +hsbe.getname ());
    }

    public void attributeremoved (Servletcontextattributeevent hsbe) {
        System.out.println (' in ServletContext removed: Name = "+hsbe.getname ());
    }

    public void attributereplaced (Servletcontextattributeevent hsbe) {
        System.out.println (' in ServletContext Replaced:name = "+hsbe.getname ());
    }

}

HttpSession, implement Httpsessionattributelistener interface:

public class Myhttpsessionattrlistener implements httpsessionattributelistener{public

    void attributeadded ( Httpsessionbindingevent hsbe) {
        System.out.println ("in httpsession added:name =" +hsbe.getname ());
    }

    public void attributeremoved (Httpsessionbindingevent hsbe) {
        System.out.println ("in httpsession removed:name =" + Hsbe.getname ());
    }

    public void attributereplaced (Httpsessionbindingevent hsbe) {
        System.out.println (' in httpsession replaced:name = ' +hsbe.getname ());
    }


ServletRequest, implement Servletrequestattributelistener interface:

public class Myservletrequestattrlistener implements servletrequestattributelistener{public

    void attributeadded (Servletrequestattributeevent hsbe) {
        System.out.println ("in servletrequest added:name =" +hsbe.getname ());
    }

    public void attributeremoved (Servletrequestattributeevent hsbe) {
        System.out.println (' in ServletRequest removed: Name = "+hsbe.getname ());
    }

    public void attributereplaced (Servletrequestattributeevent hsbe) {
        System.out.println (' in ServletRequest Replaced:name = "+hsbe.getname ());
    }

}

2.3 Status of listener objects:

For some Pojo classes, you can listen for events on Pojo class objects by implementing the Httpsessionbindinglistener interface. For example:

public class User implements httpsessionbindinglistener,serializable{

    private String username;
    private String password;
    
    Public String GetUserName () {return
        username;
    }

    public void Setusername (String username) {
        this.username = username;
    }

    Public String GetPassword () {return
        password;
    }

    public void SetPassword (String password) {
        this.password = password;
    }

    public void Valuebound (Httpsessionbindingevent hsbe) {
        System.out.println ("Valuebound Name:" +hsbe.getname ());
    } public

    void Valueunbound (Httpsessionbindingevent hsbe) {
        System.out.println ("Valueunbound Name:" + Hsbe.getname ());
    }
    

Passivation and activation of Session data:

Because the session saves a lot of important information related to the Web site, too much sessions data will degrade server performance and consume too much memory. Therefore, similar to the persistence of database objects, Web containers can also persist infrequently used session data into local files or data. These are all done by the Web container themselves and do not require user settings.

The process of serializing a session data to a local file is passivation;

When you access the content that needs to be accessed again, the local file is read and put into memory again, and the process is activation.

Similarly, as long as the implementation of the Httpseesionactivationlistener interface is to achieve passivation and activation of the event monitoring:

public class User implements Httpsessionbindinglistener, httpsessionactivationlistener,serializable{private String u
    Sername;
    
    private String password;
    Public String GetUserName () {return username;
    } public void Setusername (String username) {this.username = username;
    Public String GetPassword () {return password;
    } public void SetPassword (String password) {this.password = password; } public void Valuebound (Httpsessionbindingevent hsbe) {System.out.println ("Valuebound Name:" +hsbe.getname (
    )); } public void Valueunbound (Httpsessionbindingevent hsbe) {System.out.println ("Valueunbound Name:" +hsbe.getn
    Ame ()); } public void Sessiondidactivate (Httpsessionevent hsbe) {System.out.println ("sessiondidactivate Name:" +hsbe
    . GetSource ()); } public void Sessionwillpassivate (Httpsessionevent hsbe) {System.out.println ("Sessionwillpassivate Name:" + HsbE.getsource ()); }
    
}

servlet version and Tomcat version

First look at the matching of Tomcat's official website:

If the version does not match, then Tomcat cannot publish the project, first look at what happens when the version does not match.

I tried to create a Web project and selected the Servlet3.0 version:

Then I want to publish in TOMCAT6 and I can see the error.

JDK version is not correct .... It is a common mistake to develop a web novice who is unfamiliar with the servlet in peacetime.

Workaround:

1 when it is created, it is published directly to the Tomcat container, when the servlet lists only the versions that Tomcat supports:

2 Modify the project servlet version configuration information, the file is: Working directory \sessionexample\.settings\org.eclipse.wst.common.project.facet.core.xml

<?xml version= "1.0" encoding= "UTF-8"?>
<faceted-project>
  <runtime name= "Apache Tomcat v6.0"/ >
  <fixed facet= "java"/> <fixed facet= "Wst.jsdt.web"/> <fixed facet=
  "Jst.web"/>
  <installed facet= "java" version= "1.7"/> <installed facet=
  "Jst.web" version= "2.5"/>
  < Installed facet= "Wst.jsdt.web" version= "1.0"/>
</faceted-project>

the difference between getattribute and GetParameter

This is part of the JSP extension, often in the JSP or servlet to get the data, then getattribute and getparameter what is the difference.

1 from the source of the data:

Getattribtue gets the values in the Web container, such as:

We set a value in the servlet through the setattribute, which exists in the container and can be obtained by the GetAttribute method;

GetParameter gets the value that comes through HTTP, such as an HTTP request:

Http:localhost:8080/test/test.html?username=xingoo

There are other get and post methods that can be obtained by getparameter.

2 from the data type obtained:

GetAttribute returns an object.

GetParameter returns a string of values passed by a form or HTTP-followed parameter in the previous page.

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.