Web Listener Map Detailed

Source: Internet
Author: User
Tags apache tomcat

The listener is a very important part of Java Web development, and the knowledge involved can be referenced in the following map:

Web Listener

1 What is a Web listener?

Web listeners are special classes in Servlets 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. You can increase the processing before and after some actions to achieve monitoring.

2 Common uses for listeners

You typically use a Web listener to do the following:

Statistics online number, using Httpsessionlisener

Loading initialization information: using Servletcontextlistener

Statistics website Visit volume

Implementing Access Monitoring

3 Next, look at the creation of a listener and the execution process.

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

 Public classMyListenerImplementshttpsessionlistener{Private intUsernumber = 0;  Public voidsessioncreated (httpsessionevent arg0) {Usernumber++; Arg0.getsession (). SetAttribute ("Usernumber", Usernumber); }     Public voidsessiondestroyed (httpsessionevent arg0) {Usernumber--; Arg0.getsession (). SetAttribute ("Usernumber", Usernumber); }}

The listener is then configured in Web. XML and added in Web-app:

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

Add the number of visitors in the JSP:

<body>     people online:<%=session.getattribute ("Usernumber")%><br/></body>

When I use my browser to access it, the following results are performed:

When you open another browser access:

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

For the 3.0 version of the servlet, it is also supported in the way annotations are configured.

Then let's see what the listeners and methods are!

Classification of listeners

1 According to the listener's object division:

Depending on the listener, you can divide it into three types:

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

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

Implementation method: Directly implement Servletcontextlistener interface:

 Public class Implements servletcontextlistener{    publicvoid  contextdestroyed (servletcontextevent SCE) {    }      Public void contextinitialized (Servletcontextevent sce) {    }}

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

When a new page opens, a session is opened, the Sessioncreated method is executed, the Sessiondestroyed method is executed when the page close session expires, or when the container shuts down.

Implementation method: Directly implement Httpsessionlistener interface:

 Public class Implements httpsessionlistener{    publicvoid  sessioncreated (httpsessionevent arg0) {    }      Public void sessiondestroyed (httpsessionevent arg0) {    }}

ServletRequest monitoring: Corresponding monitoring request built-in object creation and destruction.

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

Implementation, directly implement the Servletrequestlistener interface:

 Public class Implements servletrequestlistener{    publicvoid  requestdestroyed (servletrequestevent arg0) {    }    publicvoid  requestinitialized (servletrequestevent arg0) {    }} 

2 According to the Listener event Division:

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

2.2 New, deleted, and modified listener properties:

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

ServletContext, implement Servletcontextattributelistener interface:

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

 Public classMyservletcontextattrlistenerImplementsservletcontextattributelistener{ Public voidattributeadded (servletcontextattributeevent hsbe) {System.out.println ("In ServletContext added:name =" +hsbe.getname ()); }     Public voidattributeremoved (servletcontextattributeevent hsbe) {System.out.println ("In ServletContext removed:name =" +hsbe.getname ()); }     Public voidattributereplaced (servletcontextattributeevent hsbe) {System.out.println ("In ServletContext replaced:name =" +hsbe.getname ()); }}

HttpSession, implement Httpsessionattributelistener interface:

 Public classMyhttpsessionattrlistenerImplementshttpsessionattributelistener{ Public voidattributeadded (httpsessionbindingevent hsbe) {System.out.println ("In httpsession added:name =" +hsbe.getname ()); }     Public voidattributeremoved (httpsessionbindingevent hsbe) {System.out.println ("In httpsession removed:name =" +hsbe.getname ()); }     Public voidattributereplaced (httpsessionbindingevent hsbe) {System.out.println ("In httpsession replaced:name =" +hsbe.getname ()); }}

ServletRequest, implement Servletrequestattributelistener interface:

 Public classMyservletrequestattrlistenerImplementsservletrequestattributelistener{ Public voidattributeadded (servletrequestattributeevent hsbe) {System.out.println ("In ServletRequest added:name =" +hsbe.getname ()); }     Public voidattributeremoved (servletrequestattributeevent hsbe) {System.out.println ("In ServletRequest removed:name =" +hsbe.getname ()); }     Public voidattributereplaced (servletrequestattributeevent hsbe) {System.out.println ("In ServletRequest replaced:name =" +hsbe.getname ()); }}

2.3 Monitor the status of the object:

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

 Public classUserImplementshttpsessionbindinglistener,serializable{PrivateString username; PrivateString password;  PublicString GetUserName () {returnusername; }     Public voidSetusername (String username) { This. Username =username; }     PublicString GetPassword () {returnpassword; }     Public voidSetPassword (String password) { This. Password =password; }     Public voidValuebound (httpsessionbindingevent hsbe) {System.out.println ("Valuebound Name:" +hsbe.getname ()); }     Public voidValueunbound (httpsessionbindingevent hsbe) {System.out.println ("Valueunbound Name:" +hsbe.getname ()); }    }

Passivation and activation of Session data:

because the session saves a lot of important information about the site, so too much session data will degrade the performance of the server, consuming too much memory. Thus, similar to the persistence of database objects, Web containers also persist infrequently used session data to local files or data. These are all web containers that are done by themselves and do not require user settings.

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

When the content of the session needs to be accessed again, the local file is read and put into memory again, and the process is activated.

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

 Public classUserImplementshttpsessionbindinglistener,httpsessionactivationlistener,serializable{PrivateString username; PrivateString password;  PublicString GetUserName () {returnusername; }     Public voidSetusername (String username) { This. Username =username; }     PublicString GetPassword () {returnpassword; }     Public voidSetPassword (String password) { This. Password =password; }     Public voidValuebound (httpsessionbindingevent hsbe) {System.out.println ("Valuebound Name:" +hsbe.getname ()); }     Public voidValueunbound (httpsessionbindingevent hsbe) {System.out.println ("Valueunbound Name:" +hsbe.getname ()); }     Public voidsessiondidactivate (httpsessionevent hsbe) {System.out.println ("Sessiondidactivate Name:" +Hsbe.getsource ()); }     Public voidsessionwillpassivate (httpsessionevent hsbe) {System.out.println ("Sessionwillpassivate Name:" +Hsbe.getsource ()); }    }
Servlet version vs. Tomcat version

First look at the matches given by the Tomcat website:

If the version does not match, then Tomcat will not be able to publish the project, first look at the version mismatch, what happens!

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

Then I want to publish in the Tomcat6, can see the error!

The JDK version is incorrect .... This is a common mistake in developing Web novices who are unfamiliar with servlets.

Workaround:

1 when it is created, it is published directly to the Tomcat container, at which point the servlet only lists 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>  <Runtimename= "Apache Tomcat v6.0"/>  <fixedfacet= "Java"/>  <fixedfacet= "Wst.jsdt.web"/>  <fixedfacet= "Jst.web"/>  <installedfacet= "Java"version= "1.7"/>  <installedfacet= "Jst.web"version= "2.5"/>  <installedfacet= "Wst.jsdt.web"version= "1.0"/></Faceted-project>
The difference between getattribute and getparameter

This part is the extension of the JSP, often in the JSP or servlet to obtain data, then getattribute and getparameter What is the difference?

1 from getting to the source of the data:

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

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

GetParameter gets the value from 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 through getparameter.

2 from the data type obtained:

GetAttribute returns an object.

GetParameter returns a string that is the value passed from a form in the previous page or after an HTTP parameter.

Reference

"1" MU class network, listener: http://www.imooc.com/learn/271

The difference between getattribute and getparameter in the "2" JSP: Http://wenku.baidu.com/link?url=4URJWerrusLTFRviR1sAlTH4BKc7QswiRYsso3xaYs _nzmitmv-twcniigu31k1n9hbruhfgo2-jxjpye1hgzn9rbo3b8hhzy2dn2-fcbs7

Web Listener Map Detailed

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.