The session listener is used to control the online/offline users.

Source: Internet
Author: User

Session is based on cookie technology. sessions are stored on the server (generally set the validity period), and sessionid is saved on the client. Session !! Several !!! "Key-value" pair, which can be modified/added through void setattribute (Java. Lang. string name, java. Lang. Object value)

Httpsession session = request. getsession ();

Session. setattribute ("ABC", new INTEGER (567); // new property key: ABC value: New INTEGER (567)

Session. setattribute ("jkl", new person (); // Add property key: jkl value: new person ()

Session. setattribute ("ABC", new double (5.67); // The ABC key already exists and the corresponding value of the key will be modified.

Session is essentially a set of "key-value" pairs in which "key" is stored on the client (key). The "value" in the string is saved on the server (safe deposit box) and can be of the object type.

Relationship between sessionid and Session: Key and bank safe deposit box key on client safe deposit box on server

URL rewriting: solves the problem of disabling browser cookies.

!!!!!!!!!!!!! The session becomes invalid when the browser is closed. The same session cannot be obtained during the next visit.

Instance:

Package chap03;

Import java. Io .*;

Import javax. servlet .*;

Import javax. servlet. http .*;

Public class getsession extends httpservlet

{

Public void doget (httpservletrequest request,

Httpservletresponse response)

Throws servletexception, ioexception

{

Response. setcontenttype ("text/html; charset = GBK ");

Printwriter out = response. getwriter ();

String user = "";

// No session is created here, but the created session is retrieved.

Httpsession session = request. getsession (false );

// If the session can be obtained, the user has logged on

If (session! = NULL)

{

User = (string) Session. getattribute ("ABC ");

Out. println ("Get created session ");

Out. println ("<br> ");

Out. println ("Login Name:" + User );

}

// Otherwise, it indicates that the user has not logged on. The logon page is displayed to allow the user to log on.

Else

{

Response. sendredirect ("../sessionlogin.htm ");

}

}

Public void dopost (httpservletrequest request,

Httpservletresponse response)

Throws servletexception, ioexception

{

Doget (request, response );

}

}

 

Package chap03;

Import java. Io .*;

Import javax. servlet .*;

Import javax. servlet. http .*;

Public class saveinfo extends httpservlet

{

Public void doget (httpservletrequest request,

Httpservletresponse response)

Throws servletexception, ioexception

{

// Verify the identity of the creator. The verification process is omitted here

// If a valid user generates a session to place his/her login name

// If the user name is entered, put it in the session

If (request. getparameter ("username ")! = NULL)

{

Httpsession session = request. getsession (); // creates

Session. setattribute ("ABC ",

Request. getparameter ("username"); // store "key-value pairs" on the server"

}

Response. setcontenttype ("text/html; charset = GBK ");

Printwriter out = response. getwriter ();

Out. println ("session created ");

Out. println ("<br> ");

Out. println ("go to other <a href =/" chap03.getsession/"> pages </a> ");

}

Public void dopost (httpservletrequest request,

Httpservletresponse response)

Throws servletexception, ioexception

{

Doget (request, response );

}

}

**************************************** **************************************** **********************************

**************************************** **************************************** **********************************

**************************************** **************************************** **********************************

Listening to the upper and lower limits of servlet sessions

Import java. Io. ioexception;
Import java. Io. printwriter;

Import javax. servlet. servletexception;
Import javax. servlet. http. httpservlet;
Import javax. servlet. http. httpservletrequest;
Import javax. servlet. http. httpservletresponse;
Import javax. servlet. http. httpsession;
Import javax. servlet. http. httpsessionevent;
Import javax. servlet. http. httpsessionlistener;

Public class sessionlist extends httpservlet implements httpsessionlistener {

Public void sessioncreated (httpsessionevent ex ){
Httpsession session = ex. getsession ();
// Session. setmaxinactiveinterval (10 );
Session. getservletcontext (). setattribute (session. GETID (), session. GETID ());

System. Out. println ("User ID =" + session. GETID ());

}

Public void sessiondestroyed (httpsessionevent ex ){
Httpsession session = ex. getsession ();
Session. getservletcontext (). setattribute (session. GETID (), session. GETID ());
System. Out. println (session. GETID () + "User deprecation ======== ");

}

/**
* Constructor of the object.
*/
Public sessionlist (){
Super ();
}

/**
* Destruction of the servlet. <br>
*/
Public void destroy (){
Super. Destroy (); // just puts "Destroy" string in log
// Put your code here
}

Public void doget (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception {

Response. setcontenttype ("text/html ");
Printwriter out = response. getwriter ();
Out
. Println ("<! Doctype HTML public/"-// W3C // dtd html 4.01 transitional // en/"> ");
Out. println ("<HTML> ");
Out. println ("Out. println ("<body> ");
Out. Print ("this is ");
Out. Print (this. getclass ());
Out. println (", using the get method ");
Out. println ("</body> ");
Out. println ("Out. Flush ();
Out. Close ();
}

Public void dopost (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception {
Doget (request, response );
}

Public void Init () throws servletexception {
// Put your code here
}

}
//////////////////////////////////////// //////////////////////////////////////// //////////////////////////

Add this sentence to Web. xml

 

<Listener>
<Listener-class> com. sessionlist
</Listener-class>
</Listener>

 

//////////////////////////////////////// //////////////////////////////////////// /////////////////////

**************************************** **************************************** **********************************

**************************************** **************************************** **********************************

**************************************** **************************************** **********************************

 

Significance of capturing session events:

1. Record the customer logon logs (logon and exit information) of the website)

2. Count online users

3. There are a lot more to wait ...... In short, it is very important.

Session indicates the customer's session process. When the customer logs on, an object is input to the session to track the customer's session. In servlet, if the object passed in the session is an object that implements the httpsessionbindinglistener interface (for convenience, this object is called a listener ), when it is passed in (that is, when the setattribute method of the httpsession object is called) and when it is removed (that is, when the removeattribute method of the httpsession object is called or the session
Time out) the session object will automatically call the valuebound and valueunbound methods of the listener (this is the method in the httpsessionbindinglistener interface ). From this we can see that login logs are not difficult to achieve.

Another problem is how to count the number of online users. This problem is slightly different from implementing logon logs. counting the number of online users (and their information) is to count the number of current session instances, we can add a counter (if you want to store more information, you can use an object as the counter, and then use an integer variable as the counter for the sake of simplicity ), you can add 1 to the valuebound method and 1 to the valueunbound method to calculate the number of online users. Of course, the global feature of servletcontext should be used here. (For details about servletcontext, see servlet specifications.) create a listener and store its instance in the attributes of servletcontext to ensure the uniqueness of the listener instance. When a customer logs on, first, judge whether this attribute of servletcontext is null. If it is not empty, it indicates that it has been created. directly put this attribute into the session and Add 1 to the counter; if it is null, a new listener is created and saved to the attributes of servletcontext.

Example:

Implement a listener:

// Sessionlistener. Java

Import java. Io .*;
Import java. util .*;
Import javax. servlet. http .*;

// Monitor the entire Logon Process
Public class sessionlistener implements httpsessionbindinglistener
{

Public String privateinfo = ""; // generates the listener's initialization parameter string
Private string logstring = ""; // log record string
Private int COUNT = 0; // Number of Logon counters

Public sessionlistener (string info ){
This. privateinfo = Info;
}

Public int getcount (){
Return count;
}

Public void valuebound (httpsessionbindingevent event)
{
Count ++;
If (privateinfo. Equals ("count "))
{
Return;
}
Try {
Calendar calendar = new gregoriancalendar ();
System. Out. println ("login:" + privateinfo + "time:" + calendar. gettime ());
Logstring = "/nlogin:" + privateinfo + "time:" + calendar. gettime () + "/N ";
For (INT I = 1; I <1000; I ++ ){
File file = new file ("yeeyoo. log" + I );
If (! (File. exists ()))
File. createnewfile (); // if the file does not exist, create the file
If (file. Length ()> 1048576) // if the file is larger than 1 MB, create a new file.
Continue;
Fileoutputstream Foo = new fileoutputstream ("yeeyoo. log" + I, true );
// Open the created file in append Mode
Foo. Write (logstring. getbytes (), 0, logstring. Length (); // write the log string
Foo. Close ();
Break; // exit
}
} Catch (filenotfoundexception e ){}
Catch (ioexception e ){}
}

Public void valueunbound (httpsessionbindingevent event)
{
Count --;
If (privateinfo. Equals ("count "))
{
Return;
}
Try {
Calendar calendar = new gregoriancalendar ();
System. Out. println ("logout:" + privateinfo + "time:" + calendar. gettime ());
Logstring = "/nlogout:" + privateinfo + "time:" + calendar. gettime () + "/N ";
For (INT I = 1; I <1000; I ++ ){
File file = new file ("yeeyoo. log" + I );
If (! (File. exists ()))
File. createnewfile (); // if the file does not exist, create the file
If (file. Length ()> 1048576) // if the file is larger than 1 MB, create a new file.
Continue;
Fileoutputstream Foo = new fileoutputstream ("yeeyoo. log" + I, true );
// Open the created file in append Mode
Foo. Write (logstring. getbytes (), 0, logstring. Length (); // write the log string
Foo. Close ();
Break; // exit
}
} Catch (filenotfoundexception e ){}
Catch (ioexception e ){}
}

}

Logon log implementation:

Next let's take a look at some source code of using this listener in our login servlet:

......
Httpsession session = Req. getsession (true );
......
//////////////////////////////////////// //////////////////////////
Sessionlistener =
New sessionlistener ("IP:" + Req. getremoteaddr ());
// Start a listener for each session
Session. setattribute ("listener", sessionlistener );
// Implant the listener into httpsession, which will trigger the listener to call the valuebound method,
// Record the log file.
//////////////////////////////////////// //////////////////////////

When the system exits, you only need to simply call session. removeattribute ("listener ");

You can automatically call the valueunbound method of the listener. Alternatively, this method is also called when the session time is out.

Logon count statistics:

Servletcontext session1 = getservletconfig (). getservletcontext ();
// Retrieve the servletcontext object instance
If (sessionlistener) session1.getattribute ("listener1") = NULL)
{
Sessionlistener sessionlistener1 = new sessionlistener ("count ");
// Set only once, different from that set for each session of the log file above.
// Start a global variable when the first customer connects to the server,
// After that, all customers will use the same context.
Session1.setattribute ("listener1", sessionlistener1 );
// Set the listener object to the attribute of servletcontext, which has the global validity,
// All customers can obtain its instances.
}
Session. setattribute ("listener1", (sessionlistener) session1.
Getattribute ("listener1 "));
// Retrieves the Global Object and binds it to a session,
// This will prompt the listener to call valuebound and add one to the counter.

In the subsequent programs, you can use the following code to obtain the current number of logon users at any time:

(Sessionlistener) Session. getattribute ("listener1"). getcount ()

Getcount () is a listener method, that is, to obtain the current counter value, that is, the number of logon users.

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.