who's accessing my system in jsp?

Does anyone know how to implement a jsp program which can identify who's online at the moment? I search for long time and can't find any jsp source code.I want to know their number, ip address and even their current status(such as which pages they are). Help appreciated!

   Wu
hewuAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

objectsCommented:

Add some code to all your pages to store details required from the incoming request.
0
hewuAuthor Commented:
Thanks.But I don't understand it.I am not so experienced.
I want to know who's online and display thier ip address.
That's it. Can you explain it more detailedly and give me some codes to analyze?

   Wu

       
0
objectsCommented:
Have a look at the ServletRequest class, and in particular the headers included with it. This should include most of the the information you require.
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

objectsCommented:
The bottom line is you need to track whose online yourself by analyzing details of all incoming requests.
0
cheekycjCommented:
I agree with objects.  have like an application level counter that tracks how many users are on the system.  each request can be uniquely identified so no user gets counted twice.

CJ
0
kennethxuCommented:
instead of change every jsp page, one Filter class can handle it and handle it better. a Filter class will receive any request before it reach you jsp page, so you can easily do you counting in one central place.

this is a tutorial of Filter, although it is for Orion server, the concept applys to any servlet 2.3 comply servers.
http://www.orionserver.com/tutorials/filters/1.html
0
rrzCommented:
>I want to know who's online and display thier ip address

How about using a listener?

import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionEvent;
public class SessionCounter implements HttpSessionListener {
   public void sessionCreated(HttpSessionEvent event) {
       // here is where you can add user's ip address to a data structure
   }
   public void sessionDestroyed(HttpSessionEvent event) {
      // here is where you can remove a user
   }
}

0
kennethxuCommented:
rrz, i don't think you can determine user's ip address from HttpSessionEvent. correct me if i'm wrong.
0
Howie_LyCommented:
I too agree with Objects.  For my main jsp entry page i create a record in a database (containing ip address, time of login, login type[in], and finally expirytime of session in seconds).  This way you can always expand the system for login/logout, time online, average time spent on system.

0
rrzCommented:
To Kenneth,
Good point! But maybe the solution involves both Filter and Listener classes.
The filter to get the ip address and the listener to remove it from the list of current users.
Or maybe use one object to implement both?
0
hewuAuthor Commented:
Thanks all of you. There are great points here.
As my system has many pages, I am not going to add codes for each page.I just want to write a jsp page and then  showes which IPs are online. It's a good point to create a record in a database (containing ip address, time of login, login type[in], and finally expirytime of session in seconds).Who can show me how to do that? Thanks.

 
0
hewuAuthor Commented:
Want to clarify a point.My purpose is to write a jsp page so that I can check who's accessing my system.I think I have to check how maqny session objects there are at this moment and then analyze their ip address and eliminate the repeated ip . Am I on a right track? Any other ideas or codes to finish this task?Thanks.

  Wu
0
debuchakrabartyCommented:
My dear friends,
The HttpServletRequest object has two beautiful methods getRemoteAddr() and getRemoteHost() to get the IP address of client. Infact spending sometime with JSP/Servlet API wouldn't be a bad idea :) I think objects clarified that in the very begining of this thread.

However a word of caution here: if the client is behind a firewall or proxy server, this IP address will most probably be that and not the clients machines address.
 
Regards,
Debashish
0
cheekycjCommented:
use a filter class:
http://java.sun.com/products/servlet/Filters.html
http://www.fawcette.com/javapro/2002_02/magazine/features/kjones/default_pf.asp
http://www.javaworld.com/javaworld/jw-06-2001/jw-0622-filters.html
http://www.orionserver.com/tutorials/filters/1.html

This has a sample code of using HttpSessionListener to count users:
http://www.fawcette.com/javapro/2002_02/magazine/features/bkurniawan/default_pf.asp  [listing 6]

or try a filter class like this:

package com.yourcompany.filter;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class UserCounter implements Filter {
  FilterConfig config;

  public void setFilterConfig(FilterConfig config) {
    this.config = config;
  }

  public FilterConfig getFilterConfig() {
    return config;
  }

  public void doFilter(ServletRequest req,
                       ServletResponse res,
                       FilterChain chain) {
    ServletContext context = getFilterConfig().getServletContext();
    Integer userCount = (Integer) context.getAttribute("UserCount");
    HttpSession session = req.getSession(true);
    Boolean hasBeenCounted = session.getAttribute("HasBeenCounted");
    // if this session var doesn't exist this user has not been counted yet
    if (HasBeenCounted == null) {
      if (userCount == null) {
        userCount = new Integer(1);
      }
      else {
        userCount = new Integer(userCount.intValue() + 1);
      }
      session.setAttribute("HasBeenCounted", new Boolean(true));
      context.setAttribute("UserCount", userCount);
    }
    chain.doFilter(req, res);  // no chain parameter needed here
  }
}

you have to add this to your web.xml of your application:
    <filter>
        <filter-name>UserCounter</filter-name>
        <filter-class>com.yourcompany.filter.UserCounter</filter-class>
        <description>
            This filter counts the number of users online using session and application variables.
        </description>
    </filter>
    <filter-mapping>
        <filter-name>UserCounter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


you need to deploy the filter to your webapp/WEB-INF/classes directory or in your war or a jar that your app uses.

to display the number of users online do this:

ServletContext context = getServletConfig().getServletContext();

Integer numOfUsers = (Integer) context.getAttribute("UserCount");


Its a very basic and simple implementation.  You can fiddle/fine tune and make it much more efficient and/or complex as you need it.

HTH,
CJ
0
rrzCommented:
I took Kenneth's filter idea and my listener idea and came up the following basic code. Please cut, paste, test and post a comment. I tested on Tomcat 4.1.12.


----------------------web.xml-----------------------------------------
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"    "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
           <filter>
                    <filter-name>userfilter</filter-name>
                    <filter-class>pack1.UsersFilter</filter-class>
           </filter>
           <filter-mapping>
                     <filter-name>userfilter</filter-name>
                     <url-pattern>/*</url-pattern>
           </filter-mapping>
           <listener>
                            <listener-class>pack1.UsersListener</listener-class>
           </listener>
</web-app>

---------------------UsersFilter.java------------------------------------------------------
package pack1;  
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class UsersFilter implements Filter {
  private Hashtable userstable = null;
  public void init(FilterConfig config) throws ServletException{
                         System.out.println("init of UsersFilter");
  }
  public void destroy(){}        
  public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)
                   throws ServletException, IOException {
                          HttpServletRequest req = (HttpServletRequest)request;
                          String id = req.getSession().getId();
                          String ipaddress = req.getRemoteAddr();
                          ServletContext context = req.getSession().getServletContext();
                          if(context.getAttribute("usersbean")==null){
                                     context.setAttribute("usersbean",new Hashtable());      
                          }
                          userstable = (Hashtable)context.getAttribute("usersbean");
                          userstable.put(id,ipaddress);
                          chain.doFilter(req,response);
  }
}
------------------------UsersListener.java---------------------------------------------------
package pack1;  
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class UsersListener implements HttpSessionListener {
  private Hashtable userstable = null;
  public void sessionCreated(HttpSessionEvent event) {}
  public void sessionDestroyed(HttpSessionEvent event) {
                            userstable = (Hashtable)event.getSession().getServletContext().
                                                                      getAttribute("usersbean");
                            String id = event.getSession().getId();
                            if(userstable.containsKey(id)){
                                                       userstable.remove(id);
                                                       System.out.println("id removed  " + id);
                            }
                            System.out.println("userstable  " + userstable);
  }
}
----------------------test.jsp-------------------------------------------------------
<% session.setMaxInactiveInterval(5); %>
<jsp:useBean class="java.util.Hashtable" id="usersbean" scope="application" />
usersTable<%=usersbean%>
<br/>RemoteAddr===<%=request.getRemoteAddr()%>
<br/>id===<%=request.getSession().getId()%>

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
kennethxuCommented:
hewu, what server and version are you using? Filters and Listeners requires Servlet 2.3

rrz, put context.setAttribute("usersbean",new Hashtable()); in Filter init to avoid concurrent issue, and keep a reference to usersbean to avoid unnecessary retrieve back.

and dont' forget to set sessin timeout in web.xml
0
rrzCommented:
Kenneth,
>put context.setAttribute("usersbean",new Hashtable()); in Filter init
good idea.
>keep a reference to usersbean
ok
>set sessin timeout in web.xml
I just used
><% session.setMaxInactiveInterval(5); %>  
in the JSP for testing but it seems erratic as to when Tomcat called sessionDestroyed().
0
rrzCommented:
To hewu, thanks for the points. But about kennethxu ?  He was a great help. I hope you implemented his last suggestions. He deserves points or at least a "thank you"
0
hewuAuthor Commented:
Yes. Thanks kennethxu, cheekycj ,debuchakrabarty ,objects and all of you for your great help. I appreciate your time.
This community keep me warm in my heart.Thanks again for your great experts!

   Wu
0
cheekycjCommented:
Glad to see you found a solution to work for you.  Great community effort guys :-)  Always a pleasure to participate/help with such great experts.

CJ
0
kennethxuCommented:
my pleasure to help, and thanks rrz :)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JSP

From novice to tech pro — start learning today.