In-depth analysis of JSP environment session-based online user statistics

Source: Internet
Author: User

In-depth analysis of JSP environment session-based online user statistics

As a rising star, jsp can play a certain role in the Server programming environment. It is well supported by a series of industry standards.
Closely related. Session is one of the infrastructure it provides. As a programmer, you don't mind
The client implements simple session-based user management.

There are several different processing methods for online users.

One is that foliar refresh is controlled by the user, and the server controls a timeout time, for example, 30 minutes. After the time, the user
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 need to submit
Login again. If the original leaves are forced to expire, your work may be lost. In implementation
This is the simplest mode, which is implemented by the server by default.

Another way is that the site uses a frame structure, and a frame or hidden IFRAME is constantly refreshing.
It will never be kicked out, but the server needs to set a daze time to determine whether you are online.
If you do not refresh any other leaves except the automatically refreshed ones, you will think that you are no longer
Line. The typical method is xici.net. Its advantage is that it can be implemented through constant refreshing.
Similar to the server-push function, for example, 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 be used to change the attribute of an httpsession.
Notify you of the class. Httpsessionattributelistener is introduced in 2.3.
They 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), and
Public void valueunbound (httpsessionbindingevent event ).
When you execute session. addattribute (string, object ),
The class of the httpsessionbindinglistener interface is added as attribute. 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, after each user login, in the vector of Attribute "activesessions" in the application
Will add a record.
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 in JSP.
Object.
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%20does%20not%20exist.");return;}catch (InvalidPasswordException e2){response.sendRedirect("InsufficientPrivilege.jsp?detail=Invalid%20Password");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. Where
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. For online user list paging and other functions,
It is irrelevant to this article and will not be discussed.
This is an example of a non-Refresh model, depending on the Session Timeout mechanism. My colleague sonymusic pointed out that
Sometimes, due to different manufacturers' ideas, this may be untrusted. To meet this requirement, you must
When each leaf is refreshed, the current user determines whether the last time used has exceeded a specified time value.
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.