Servlet Implements online user tables

Source: Internet
Author: User

In the course of learning the servlet , we learned how to implement online user tables with Servlets.

Only the server is on the status of the presence of online user table, in the case of the server shutdown naturally there is no online user table statement; Therefore, the landlord thinks that the information on the online user's table is not to be persisted, the cache of the server can be saved directly.

Since it's stored in the cache, there are four scopes in the Java Web that we use to store things:PageContext, request, session,application Since our online users show that it is natural that there should be a scope application that everyone can see, there should be an online user table in the application when the server is powered on, and after that the table is modified.

  

1  Public void contextinitialized (servletcontextevent arg0)   2          // TODO auto-generated Method Stub 3         Hashmap<string, visitor> onlinemap=new hashmap<string, visitor>();//Create an online user table  4         ServletContext application= arg0.getservletcontext ();//Get Application5         Application.setattribute ("Online", onlinemap);//Deposit Online User Table application6     }

Clear this thing, you can follow the user arrived at the site after a series of processes to consider. First, the user arrives at the website, the server background processing, then the front desk can see the "Online User table" on the new online user, and then the user left, the server background processing, the last front desk can see the "Online User table" on the reduction of an online user. So, that is, the realization of the online user table. The basic flow is there, and then the analysis is implemented:

1. User arrives

(1) According to the above analysis, the user arrived we must put the user's relevant information into the application to facilitate the use; then how to judge the user? Since the user into the site, the server will definitely assign him a session of space, know this is good to do; we can build a session of the listener to listen to The session creation is the sessioncreated() method, in which we can write the code we want to write;

1  Public voidsessioncreated (httpsessionevent arg0) {2 3          //TODO auto-generated Method Stub4 5HttpSession session=arg0.getsession ();6 7Session.setmaxinactiveinterval (1*60);//to easily see the result of the session failure, set the session expiration time to 60 seconds, the default is 30 minutes8 9Visitor v=NewVisitor ();//Create a new visitor object, save visitor informationTen  OneV.setip (Request.getremoteaddr ());//Get guest IP A  -V.setcomefrom (Request.getheader ("Referer"));//get the URL of the visitor -  theV.setvisittime (NewDate ());//Log guest access times -  -ServletContext application= arg0.getsession (). Getservletcontext ();//Get Application -  +@SuppressWarnings ("Unchecked") -  +Hashmap<string,visitor> onlinmap= (hashmap<string, visitor>) application.getattribute ("online");//Remove the Online user table from the application A  atOnlinmap.put (Session.getid (), v);//put the new visitor information into the online user table -  -Application.setattribute ("online", Onlinmap);//Deposit The updated online user form into application -  -}

(2) The front desk should also be able to read the information in the application;

Since application is the built-in object of JSP, we don't need to get it, we can use it directly .

1<table>2 3<!--headers--4 5<tr>6 7<th> User name </th>8 9<th> Access Time </th>Ten  One<th> User ip</th> A  -<th> from Page </th> -  the</tr> -  -<% -  +@SuppressWarnings ("Unchecked") -  +Hashmap<string, visitor> onlinmap= (hashmap<string, visitor>) application.getattribute ("online");//Remove Online User table A  atSet<string> Key=onlinmap.keyset ();//Remove the key collection for the online user table -  -Iterator<string> It=key.iterator ();//remove key one by one from the key collection into the iterator object -  -      while(It.hasnext ())//one by one online user tables by traversing all keys in the online user table -  in     { -  toString id=It.next (); +  -Visitor v=onlinmap.get (ID); the  *%> $ Panax Notoginseng<tr> -  the<td><%=v.getid ()%></td> +  A<td><%=v.getvisittime ()%></td> the  +<td><%=v.getip ()%></td> -  $<td><%=v.getcomefrom ()%></td> $  -</tr> -  the<% - Wuyi     } the  -%> Wu  -</table> About  $  

2. User left

(1) We have to remove the user's information from the application.

Generally we cannot judge the exact time of the user leaving, but we know that as long as the session expires, the user must leave, so we can use The session Listener to monitor The expiration of the session, which is the sessiondestroyed() method.

1   Public voidsessiondestroyed (httpsessionevent arg0) {2 3          //TODO auto-generated Method Stub4 5ServletContext application=arg0.getsession (). Getservletcontext ();6 7@SuppressWarnings ("Unchecked")8 9Hashmap<string, visitor> onlinmap= (hashmap<string, visitor>) application.getattribute ("online");Ten  OneString id=arg0.getsession (). GetId ();//get ID of invalid session A  -Visitor v=onlinmap.get (ID); -  theV.setlefttime (NewDate ());//record the time of Session failure (user left) -  -Onlinmap.remove (ID);//remove a departing user from an online user table -  +      //because the compound type is assigned with a "=" value by changing the pointer, the map that was changed in the following way is a direct change to the original map in the application, so there is no need to Application.setattribute ("online", ONLINMAP); this statement. -  +     } A  at  

In this way , the online user table is implemented using a servlet.

Add:

1.Visitor Solid class

Visitor entity class based on the database Visitor table is built, is a JavaBean;

2. access to request

A request Listener can be built via request= (httpservletrequest) arg0.getservletrequest (); To get the request,if you want to use it globally, just define the request as a property of the class, but be aware that the request is The instantiation of the HttpServletRequest class is not servletrequest;

Servlet Implements online user tables

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.