On-line user statistics analysis based on session in JSP

Source: Internet
Author: User
Tags time limit advantage

JSP as an Up-and-comer can occupy a certain position in the server programming environment, and it is closely related to the good support of a series of industry standards. Session is one of the infrastructure that it provides. As a programmer, you can easily implement simple session-based user management by not mind how the client is implemented. There are now several different ways to deal with online users.

One is the page refresh by the user control, server-side control of a timeout such as 30 minutes, to the time after the user did not move to be kicked out. The advantage of this method is that if the user forgets to quit, it can prevent others from malicious action. The downside is that if you're doing a time consuming thing, exceeding the time limit, you may have to face the landing again when you submit. If the original leaf is forced to fail, it is possible to lose the work you do. In the perspective of implementation, this is the simplest, the server side is the default implementation of this pattern.

Another way is, the site uses a frame structure, there is a frame or hidden iframe constantly refreshed, so you will never be kicked out, but the server to determine whether you are online, you need to set a daze time, If more than this daze time you in addition to this automatic refresh of the page does not refresh other pages, I think you are no longer online. The typical way to take this approach is xici.net. His advantage is that you can use the constant refresh to implement some similar server-push functions, such as sending messages between netizens.

Regardless of the pattern, additional work is required to enable browsing of all current online users. The Servlet API does not have an API for the session list.

What can be used is the listener. The Servlet 2.2 and 2.3 specifications are slightly different here. The Httpsessionbindinglistener in 2.2 enables you to notify your class when the attribute changes in a httpsession. And 2.3 also introduced httpsessionattributelistener. Since I am using visual age for Java 4 and JRun Server 3.1, they do not directly support the programming of Servlet 2.3, I'm using Httpsessionbindinglistener here.

What needs to be done involves doing a new class to implement the Httpsessionbindinglistener interface. This interface has two methods:

public void Valuebound (Httpsessionbindingevent event)

public void Valueunbound (Httpsessionbindingevent event)

When you perform Session.addattribute (string,object), if you have added a class that implements the Httpsessionbindinglistener interface to Attribute,session will notify you of the class , call your Valuebound method. Instead, the Session.removeattribute method corresponds to the Valueundound method.

public class Httpsessionbinding implements Javax.servlet.http.HttpSessionBindingListener

{

ServletContext application = null;

Public httpsessionbinding (ServletContext application)

{

Super ();

if (Application ==null)

throw new IllegalArgumentException ("Null application is not accept.");

this.application = Application;

}

public void Valuebound (Javax.servlet.http.HttpSessionBindingEvent e)

{

Vector activesessions = (vector) application.getattribute ("Activesessions");

if (activesessions = null)

{

Activesessions = new Vector ();

}

Jdbcuser Sessionuser = (jdbcuser) e.getsession (). getattribute ("user");

if (Sessionuser!= null)


{

Activesessions.add (E.getsession ());

}

Application.setattribute ("Activesessions", activesessions);

}

public void Valueunbound (Javax.servlet.http.HttpSessionBindingEvent e)

{

Jdbcuser Sessionuser = (jdbcuser) e.getsession (). getattribute ("user");

if (Sessionuser = null)

{

Vector activesessions = (vector) application.getattribute ("Activesessions");

if (activesessions!= null)

{

Activesessions.remove (E.getsession (). GetId ());

Application.setattribute ("Activesessions", activesessions);

}

}

}

}

Suppose that the Jdbcuser class is an arbitrary user class. When performing a user login, add both the user class and the Httpsessionbinding class to the session.

In this way, each time the user logs in, the application "activesessions" in the vector will add a record. Whenever the session times out, the valueunbound is triggered, and in this vector the session that will be timed out is deleted.

public void Login ()

Throws Aclexception,sqlexception,ioexception

{

/* Get JDBC User Class */

if (user!= null)

{

Logout ();

}

{

If session time out, or user didn ' t login, save the target URL temporary.

Jdbcuserfactory uf = new Jdbcuserfactory ();

if ((This.request.getParameter ("UserID") ==null) | | (This.request.getParameter ("password") ==null)

{

throw new Aclexception ("Please input a valid userName and password.");

}

Jdbcuser user = (jdbcuser) uf. Userlogin (

This.request.getParameter ("UserID"),

This.request.getParameter ("password"));

User.touchlogintime ();

This.session.setAttribute ("user", user);

This.session.setAttribute ("Bindingnotify", New Httpsessionbinding (application));

}

}

Login, the user and this bindingnotofy purpose of the class are added to the session. When logout, you should take the initiative to delete this session in the vector of activesessions.

public void Logout ()

Throws Sqlexception,aclexception

{

if (This.user = = null && this.session.getAttribute ("user") ==null)

{

Return

}

Vector activesessions = (vector) this.application.getAttribute ("Activesessions");

if (activesessions!= null)

{

Activesessions.remove (this.session);

Application.setattribute ("Activesessions", activesessions);

}

Java.util.Enumeration e = This.session.getAttributeNames ();

while (E.hasmoreelements ())

{

string s = (string) e.nextelement ();

This.session.removeAttribute (s);

}

This.user.touchLogoutTime ();

This.user = null;

}

The two functions are in a Httpsessionmanager class. This class refers to the application global object in the JSP. The other code for this class has nothing to do with this article and is quite long, so I won't post it.

Let's look at how to use JSP inside.

Assuming that a form for a login is submitted to dologin.jsp, the form contains username and password fields. Excerpt part fragment:

<%

Httpsessionmanager HSM = new Httpsessionmanager (application,request,response);

Try

{

Hsm.login ();

}

catch (Usernotfoundexception e)

{

Response.sendredirect ("insufficientprivilege.jsp?detail=user%20does%20not%20exist.");

Return

}

catch (invalidpasswordexception E2)

{

Response.sendredirect ("Insufficientprivilege.jsp?detail=invalid%20password");

Return

}

catch (Exception E3)

{

%> error:<%=e3.tostring ()%>

Press here to Relogin.

<% return;

}

Response.sendredirect ("index.jsp");%>

Let's take a look at how we can get a list of users currently online.

sessionid

user

login time

last Access time

<%

Vector activesessions = (vector) application.getattribute ("Activesessions");

if (activesessions = null)

{

Activesessions = new Vector ();

Application.setattribute ("Activesessions", activesessions);

}

Iterator it = Activesessions.iterator ();

while (It.hasnext ())

{

HttpSession sess = (HttpSession) it.next ();

Jdbcuser Sessionuser = (jdbcuser) sess.getattribute ("User");

String userId = (sessionuser!=null)? Sessionuser.getuserid (): "None";

%>

<%= beacondate.getinstance (New Java.util.Date (Sess.getcreationtime ())). Getdatetimestring ()%>

<%= beacondate.getinstance (New Java.util.Date (Sess.getlastaccessedtime ())). Getdatetimestring ()%>

<%

}

%>

The above code takes out the activesessions from the application and shows the specific time. Where the Beacondate class is assumed to be a class that formats the time.

In this way, we have a framework for viewing the list of online users. The functions of online user list paging are irrelevant to this article and are not discussed.

This is an example of a non-refresh model that relies on the timeout mechanism of the session. My colleague Sonymusic pointed out that many times this may be unreliable due to the different ideas of the various manufacturers. In view of this requirement, it is necessary to determine whether the current user has exceeded a predetermined time value from the last use time when each leaf is refreshed. This is essentially the realization of the session timeout itself. If you need to implement a refresh model, you must use this method of refreshing the individual foliage.




Related Article

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.