JSP user statistical analysis Session-based online

Source: Internet
Author: User

As a rising star, JSP plays a certain role in the Server programming environment and is closely related to its good support of a series of industry standards. Session is one of the infrastructure it provides. As a programmer, you can easily implement simple session-based user management without worrying about how the client is implemented. There are several different processing methods for online users.

One is that the user controls the foliar refresh, and the server controls a timeout time, for example, 30 minutes. After the time, the user is kicked out without any action. The advantage of this method is that if the user forgets to quit, it can prevent malicious operations by others. The disadvantage is that if you are doing a very time-consuming task that exceeds this time limit, you may have to log on again when submit. If the original leaves are forced to expire, your work may be lost. From the implementation perspective, this is the simplest, and the default implementation on the Server side is this mode.

Another way is that the site uses a Frame structure, and a Frame or hidden iframe is constantly refreshing, so that you will never be kicked out, but the server is trying to determine whether you are online, you need to set a daze time. If you have not refreshed any other leaves except the automatically refreshed ones, you will think that you are no longer online. The typical method is xici.net. Its advantage is that it can use constant refreshing to implement some functions similar to server-push, such as sending messages between netizens.

No matter which mode, some additional work is required to browse all online users. The servlet API does not obtain the Session List API.

The Listener. Servlet 2.2 and 2.3 specifications are slightly different here. HttpSessionBindingListener in 2.2 can notify you of classes when the Attribute in an HTTPSession changes. HttpSessionAttributeListener is also introduced in 2.3. since the environments I use are Visual age for java 4 and JRun server 3.1, they do not directly support Servlet 2.3 programming. Here I use HttpSessionBindingListener.

What needs to be done includes creating 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 execute Session. when addattriund (String, Object) is used, if you have added a class that implements the HttpSessionBindingListener interface as Attribute, the Session will notify you of the class and call your valueBound method. On the contrary, 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 );
}
}
}
}

Assume that the JDBCUser class is an arbitrary User class. During User logon, add both the User class and HttpSessionBinding class to the Session.
In this way, each time a user logs on, a record will be added to the vector attribute "activeSessions" in the application. Whenever the session times out, valueUnbound is triggered. In this vector, delete the session to be timed out.

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 ));
}
}

When using Login, add the User and the BindingNotofy class to the session. When logout is used, you need to delete the session in the activeSessions vector.

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;
}

These two functions are located in an HttpSessionManager class. This class references the application Global Object in jsp. Other codes of this class have nothing to do with this article, and I will not post it.

Next let's take a look at how to use jsp.

Assume that a login form is submitted to doLogin. jsp, which contains the UserName and password fields. Excerpt:

<%
HttpSessionManager hsm = new HttpSessionManager (application, request, response );
Try
{
Hsm. login ();
}
Catch (UserNotFoundException e)
{
Response. sendRedirect ("InsufficientPrivilege. jsp? Detail = User % 20 does % 20not % 20exist .");
Return;
}
Catch (InvalidPasswordException e2)
{
Response. sendRedirect ("InsufficientPrivilege. jsp? Detail = Invalid % 20 Password ");
Return;
}
Catch (Exception e3)
{
%> Error: <% = e3.toString () %> <br>
Press <a href = "login. jsp"> Here </a> to relogin.
<% Return;
}
Response. sendRedirect ("index. jsp ");
%>

Now let's take a look at how we get a list of online users.

<Body bgcolor = "# FFFFFF">
<Table cellspacing = "0" cellpadding = "0" width = "100%">

<Tr>
<Td style = 'width: 24px '> SessionId
</Td>
<Td style = 'width: 80px '> User
</Td>
<Td style = 'width: 80px '> Login Time
</Td>
<Td style = 'width: 80px '> Last access Time
</Td>
</Tr>
<%
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 ";
%>
<Tr>
<Td nowrap = ''> <% = sess. getId () %> </td>
<Td nowrap = ''> <% = userId %> </td>
<Td nowrap = ''>
<% = BeaconDate. getInstance (new java. util. Date (sess. getCreationTime (). getDateTimeString () %> </td>
<Td class = "<% = stl %> 3" nowrap = ''>
<% = BeaconDate. getInstance (new java. util. Date (sess. getLastAccessedTime (). getDateTimeString () %> </td>
</Tr>
<%
}
%>
</Table>
</Body>

The above code extracts activeSessions from the application and displays the specific time. The BeaconDate class is assumed to be the formatting time class.

In this way, we get a framework for viewing the list of online users. This article will not discuss online user list paging and other functions.

This is an example of a non-Refresh model, depending on the session Timeout mechanism. My colleague sonymusic pointed out that many times, due to different manufacturers' ideas, this may be untrusted. To meet this requirement, You need to judge whether the current user has exceeded a specified time value from the last time used during each foliar refresh. In essence, session timeout is achieved by yourself. If you need to refresh the model, you must use this method to refresh each leaf.

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.