Get the number of sessions in JSP or Servlet

Source: Internet
Author: User

Many netizens have asked how to make online community staff display problems, which is also a difficult problem. I have learned and practiced programming in these fields for a long time. I don't mean that I have technology, but I have some experience. I have encountered many problems in solving these problems, and I have always solved them.
This is not about code implementation of a program, but more importantly, it is about principles and ideas, because everyone knows how to do this, there is no technical problem, but it is just a syntactic unfamiliar.
In fact, it is very easy to determine whether a user logs on. Just add "set the user to online" to the login program, this can be done using SQL update or other append operations such as text files. If you set COOIKE logon when logging on, you only need to update the page or publish a post.
In fact, netizens think it is difficult to know how users have left the community. The following are some mistakes made by beginners.
Method 1: Of course, some netizens will do "quit the Community" in the community. If some users are busy or have fast hands, the browser will be closed directly. In the program's view, this user did not exit the community at all.
Method 2: in this case, some netizens use JavaScript to execute an unload event and exit a window when closing the browser, to execute the update, which may be to solve the problem of direct shutdown. However, the netizen did not consider that if the post or article is too long and the user wants to take a good look after breaking the line, then he just closed the browser after reading all the posts or articles. The program that jumps out of the window page is not executed.
Error Method 3: The session is used as an example. Generally, the server has a Session expiration time. For example, if IIS is set to 20 minutes, some netizens judge it based on the Session, which obviously does not work, the result is the same as the error method 2.
So what if it is the correct method. So far, there is no convenient and accurate method for this. Unless you use Job transactions, it is almost impossible, because it is free of charge, even the charged home page space won't let you do this. Therefore, it can only be implemented through Common commands.
But its limitation is that it is not accurate, but we can make it closer to precision.
The following uses the SQL SERVER in the IIS environment as an example. Other statements, such as PHP + MYSQL, JSP + ms SQL SERVER, do not need to be changed.
The program fragment is used in the example. For example, in the users table, except for the basic username field name), the bit type can be used for the online field. There is also a logintime field for Logon Time, And the logouttime field for the last operation time, all of which are of the datetime type. The detailed functions will be discussed later.
First, when a user logs on to the system, the value of the Session ("name") field or the value of cookies ("club") ("name") must be generated, this allows SQL to know the user's record on any page in the community during operations. Next, update the user's offline online field and logintime field. The statement is as follows:
Conn.exe cute ("Update users set online = 1, logintime = '" & now & "'where name ='" & session ("name ")&"'")
The purpose of this statement is to set the online user to true when the user logs on, and then set the current operation time to the present. This statement is also used when users browse posts or articles, because it may be more accurate.
Add a sentence after these statements.
Conn.exe cute ("Update users set online = 0 where diffdate (" "n" ", logintime, '" & now () & "')> 10 ")
This statement compares the last operation time of a user with the current time. If it is more than 10 minutes, all users are set to offline.
Well, the key is the two statements. Is it very simple? After talking about this, what you want to know is the implementation principle, not the code. I believe that you can now easily make programs displayed by online staff of PHP + MYSQL and JSP + database.
Finally, you can use "select name from users where online = 1" to call online users. Then, it is displayed that it is okay. Oh...
***************************
Namespace OnlineCount
{
Using System;
Using System. Data;
Using System. Drawing;
Using System. Web;
Using System. Web. UI. WebControls;
Using System. Web. UI. HtmlControls;
///


/// Summary of Online.
///
Public class Online: System. Web. UI. UserControl
{
Protected System. Web. UI. WebControls. Label Label1;
Private void Page_Load (object sender, System. EventArgs e)
{
If (Application ["online"] = null)
{
DataTable dtnew = new DataTable ();
Dtnew. Columns. Add ("userid", typeof (string ));
Dtnew. Columns. Add ("lastaccesstime", typeof (DateTime ));
Application ["online"] = dtnew;
}
// DataTable dt = (DataTable) Application ["online"];
DataTable dt = Application ["online"] as DataTable;
DataRow [] rows = dt. Select ("userid = '" + Session. SessionID + "'");
If (rows. Length = 1)
{
DataRow dr = rows [0];
Dr ["lastaccesstime"] = DateTime. Now;
}
Else
{
DataRow dr = dt. NewRow ();
Dr ["userid"] = Session. SessionID;
Dr ["lastaccesstime"] = DateTime. Now;
Dt. Rows. Add (dr );
}
For (int I = 0; I <dt. Rows. Count; I ++)
{
DataRow dr = dt. Rows [I];
TimeSpan t = DateTime. Now-Convert. ToDateTime (dr ["lastaccesstime"]);
If (t. Seconds> 8)
{
Dr. Delete ();
}
}
Dt. AcceptChanges ();
This. Label1.Text = dt. Rows. Count. ToString ();
}
# Code generated by region Web Form Designer
Override protected void OnInit (EventArgs e)
{
//
// CODEGEN: This call is required by the ASP. NET Web form designer.
//
InitializeComponent ();
Base. OnInit (e );
}
///
/// The designer supports the required methods-do not use the code editor
/// Modify the content of this method.
///
Private void InitializeComponent ()
{
This. Load + = new System. EventHandler (this. Page_Load );
}
# Endregion
}
}
* ********** OnlineUser. java ************
Package org. sunxin. lesson. jsp. ch09.online;
Import javax. servlet .*;
Import java. io .*;
Import javax. servlet. http .*;
Import java. util. Enumeration;
Public class OnlineUser extends HttpServlet
{
Public void doGet (HttpServletRequest req, HttpServletResponse resp)
Throws ServletException, IOException
{
Req. setCharacterEncoding ("gb2312 ");
String name = req. getParameter ("user ");
String pwd = req. getParameter ("password ");

If (null = name | null = pwd | name. equals ("") | pwd. equals (""))
{
Resp. sendRedirect ("login.html ");
}
Else
{
HttpSession session = req. getSession ();
User user = (User) session. getAttribute ("user ");
If (null = user |! Name. equals (user. getName ()))
{
User = new User (name );
Session. setAttribute ("user", user );
}

Resp. setContentType ("text/html; charset = gb2312 ");
PrintWriter out = resp. getWriter ();

Out. println ("Welcome "+ Name +"Login ");
UserList ul = UserList. getInstance ();
Out. println ("
List of online users:
");
Enumeration Enums = ul. getUserList ();
Int I = 0;
While (enums. hasMoreElements ())
{
Out. println (enums. nextElement ());
Out. println ("");
If (++ I = 10)
{
Out. println ("
");
}
}
Out. println ("
Current number of online users: "+ I );
Out. println ("

Log out ");
Out. close ();
}
}

Public void doPost (HttpServletRequest req, HttpServletResponse resp)
Throws ServletException, IOException
{
DoGet (req, resp );
}
}
* *********** LogoutServlet. java ************
Package org. sunxin. lesson. jsp. ch09.online;
Import javax. servlet .*;
Import java. io .*;
Import javax. servlet. http .*;
Public class LogoutServlet extends HttpServlet
{
Public void doGet (HttpServletRequest req, HttpServletResponse resp)
Throws ServletException, IOException
{
Resp. setContentType ("text/html; charset = gb2312 ");

HttpSession session = req. getSession ();
User user = (User) session. getAttribute ("user ");
Session. invalidate ();

PrintWriter out = resp. getWriter ();
Out. println ("");
Out. println (user. getName () + ", you have logged out.
");
Out. println ("Log on again ");
Out. println ("");
Out. close ();
}
}
* *********** User. java ************
Package org. sunxin. lesson. jsp. ch09.online;
Import javax. servlet. http. HttpSessionBindingListener;
Import javax. servlet. http. HttpSessionBindingEvent;
Public class User implements HttpSessionBindingListener
{
Private String name;
Private UserList ul = UserList. getInstance ();

Public User ()
{
}
Public User (String name)
{
This. name = name;
}
Public void setName (String name)
{
This. name = name;
}
Public String getName ()
{
Return name;
}
Public void valueBound (HttpSessionBindingEvent event)
{
Ul. addUser (name );
}
Public void valueUnbound (HttpSessionBindingEvent event)
{
Ul. removeUser (name );
}
}
* ********** UserList. java ************
Package org. sunxin. lesson. jsp. ch09.online;
Import java. util. Vector;
Import java. util. Enumeration;
Public class UserList
{
Private static final UserList userList = new UserList ();
Private Vector V;

Private UserList ()
{
V = new Vector ();
}
Public static UserList getInstance ()
{
Return userList;
}

Public void addUser (String name)
{
If (name! = Null)
V. addElement (name );
}

Public void removeUser (String name)
{
If (name! = Null)
V. remove (name );
}

Public Enumeration GetUserList ()
{
Return v. elements ();
}

Public int getUserCount ()
{
Return v. size ();
}
}
****************************
The idea of Java code is to place all login users in the collection.
After a user logs in successfully, the user is added to the user list. After the user exits, the user is removed from the user list.
Lz pay attention to the interfaces implemented by the User class and the following two methods:
// Notifies the object when it is bound to the session.
Public void valueBound (HttpSessionBindingEvent event)
{
Ul. addUser (name );
}
// Notifies the object when it is deleted from the session.
Public void valueUnbound (HttpSessionBindingEvent event)
{
Ul. removeUser (name );
}

  1. Analysis of Java Servlet Construction System
  2. HTTP Servlet Application Programming Interface
  3. Let's talk about how to understand the concepts of JSP and Servlet.
  4. Optimize Servlet configuration for web. xml slimming
  5. What is ServletResponse?

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.